手写Promise - 实现一个基础的Promise
手写Promise - 实例方法catch、finally
手写Promise - 常用静态方法all、resolve、reject、race
上一篇文章手写了一个基础的Promise,我们继续来完善它,为其添加经常用到的catch和finally方法
catch & finally
catch() 方法返回一个Promise,并且处理拒绝的情况。我们知道then方法的第二个参数其实就是干这个用的,catch只是一个别名。
finally() 方法返回一个Promise。在promise结束时,无论结果是fulfilled或者是rejected,都会执行指定的回调函数。和catch一样,也只是对then的一个简写,相当于是传入的函数既是onFulfilled也是onRejected。
有一点需要注意,finally和catch方法只是then的一个别名,实际上返回的还是一个promise,完全可以这样写:promise.then().finally().then().catch().then()
我们把上一章节的代码拷过来,然后向里面添加catch和finally方法。
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