手写Promise
2019-10-28 本文已影响0人
Victor_818
1. 简易版Promise,只能调用一次then,不能链式调用:
class Promise {
constructor(executor) {
this.status = 'pending';
this.value = undefined;
this.reson = undefined;
// 成功存放的数组
this.onResolvedCallbacks = [];
// 失败存放法数组
this.onRejectedCallbacks = [];
// 成功时调用
let resolve = value => {
setTimeout(() => {
if (this.status === 'pending') {
this.status = 'fulfilled';
this.value = value;
// 一旦resolve执行,调用成功数组的函数
this.onResolvedCallbacks.forEach(fn => {
fn();
});
}
});
};
// 失败时调用
let reject = reson => {
setTimeout(() => {
if (this.status === 'pending') {
this.status = 'rejected';
this.reson = reson;
// 一旦reject执行,调用失败数组的函数
this.onRejectedCallbacks.forEach(fn => {
fn();
});
}
});
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
onRejected =
typeof onRejected === 'function'
? onRejected
: err => {
throw err;
};
setTimeout(() => {
if (this.status === 'fulfilled') {
onFulfilled(this.value);
}
});
setTimeout(() => {
if (this.status === 'rejected') {
onRejected(this.reson);
}
});
if (this.status === 'pending') {
this.onResolvedCallbacks.push(() => {
setTimeout(() => {
onFulfilled(this.value);
});
});
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
onRejected(this.reson);
});
});
}
}
}
let premise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('0.123');
});
});
premise.then(res => {
console.log(res); // 0.123
});