class Promise {
constructor(executor) {
if (typeof executor !== 'function') {
throw new Error('Executor must be a function');
}
this.state = 'PENDING';
this.chained = []; chained用来储存promise执行完成以后,需要被依次调用的一系列函数
const resolve = res => {
if (this.state !== 'PENDING') {
return;
}
this.state = 'FULFILLED';
this.value = res;
for (const { onFulfilled } of this.chained) {
onFulfilled(res);
}
};
const reject = err => {
if (this.state !== 'PENDING') {
return;
}
this.state = 'REJECTED';
this.value = err;
for (const { onRejected } of this.chained) {
onRejected(err);
}
};
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
then(onFulfilled, onRejected) {
if (this.state === 'FULFILLED') {
onFulfilled(this.value);
} else if (this.state === 'REJECTED') {
onRejected(this.value);
} else {
this.chained.push({ onFulfilled, onRejected });
}
}
}
手写Promise
最新推荐文章于 2022-05-16 09:35:24 发布