先来回顾一下,上一章节之后的代码。class WPromise {
static pending = 'pending';
static fulfilled = 'fulfilled';
static rejected = 'rejected';
constructor(executor) {
this.status = WPromise.pending; // 初始化状态为pending
this.value = undefined; // 存储 this._resolve 即操作成功 返回的值
this.reason = undefined; // 存储 this._reject 即操作失败 返回的值
// 存储then中传入的参数
// 至于为什么是数组呢?因为同一个Promise的then方法可以调用多次
this.callbacks = [];
executor(this._resolve.bind(this), this._reject.bind(this));
}
// onFulfilled 是成功时执行的函数
// onRejected 是失败时执行的函数
then(onFulfilled, onRejected) {
// 返回一个新的Promise
return new WPromise((nextResolve, nextReject) => {
// 这里之所以把下一个Promsie的resolve函数和reject函数也存在callback中
// 是为了将onFulfilled的执行结果通过nextResolve传入到下一个P