本文参考promise略有修改并简化,直接上代码了。
class Promise {
constructor(executor) {
this.state = 'pending';
this.value = undefined;
this.reason = undefined;
// 成功存放的数组
this.onResolvedCallbacks = [];
// 失败存放法数组
this.onRejectedCallbacks = [];
let resolve = value => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
console.log('fulfilled');
// 一旦resolve执行,调用成功数组的函数
console.log(this.onResolvedCallbacks);
this.onResolvedCallbacks.forEach(fn => fn());
}
};
let reject = reason => {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
console.log('rejected');
// 一旦reject执行,调用失败数组的函数
this.onRejectedCallbacks.forEach(fn => fn());
}
};
try {
// 执行这个方法 (resolve, reject) => {resolve();} //函数体里执行 resolve();
executor(resolve, reject); // 从这里传进resolve 和 reject方法
} catch (err) {
console.log('catch');
reject(err);
}
}
then(onFulfilled, onRejected) {
console.log('then state', this.state);
// executor 函数体里,如果有错误; 会执行try catch里的 reject方法,执行then this.state就是rejected
// 如果没错误且没异步,resolve this.state就是fulfilled
// 如果没错误且有异步,this.state就是pending
if (this.state === 'fulfilled') {
onFulfilled(this.value);
};
if (this.state === 'rejected') {
onRejected ? onRejected(this.reason) : '';
};
// 当状态state为pending时
if (this.state === 'pending') {
// onFulfilled传入到成功数组
this.onResolvedCallbacks.push(() => {
onFulfilled(this.value);
});
// onRejected传入到失败数组
this.onRejectedCallbacks.push(() => {
onRejected ? onRejected(this.reason) : '';
});
}
return this;
}
catch(onRejected) {
console.log(this.state);
if (this.state === 'rejected') {
onRejected(this.reason);
};
if (this.state === 'pending') {
// onRejected传入到失败数组
this.onRejectedCallbacks.push(() => {
onRejected(this.reason);
});
}
}
}
// resolve方法
Promise.resolve = function (val) {
return new Promise((resolve, reject) => {
resolve(val);
});
};
// reject方法
Promise.reject = function (val) {
return new Promise((resolve, reject) => {
reject(val);
});
};
Promise.all = function (promises) {
return new Promise((resolve, reject) => {
let results = [];
let count = promises.length;
for (let i = 0; i < promises.length; i++) {
promises[i].then((res) => {
// results.push(res) // 这种方式顺序确保不了
results[i] = res; // 这个为了保持顺序一致!
count--;
if (count === 0) {
resolve(results);
}
}, reject); // 这个reject作用在于里层有什么错,都通过外层的 Promise reject出来
/* }).catch((err) => { // 上一行等于这3行,这3行好理解一点。
reject(err)
}) */
}
});
};