自己封装一个Promise
代码:https://github.com/fu-x/promise
首先我们需要对Promise进行分析
声明一个MyPromise类
class MyPromise {
} // 声明MyPromise类
Promise的三种状态:pending、fulfilled、rejected
我们要在类里定义三个静态常量
static PENDING = 'pending'; // pending状态表示正在执行中
static FULFILLED = 'fulfilled'; // fulfilled状态表示执行成功
static REJECTED = 'rejected'; // rejected状态表示执行失败
Promise默认方法(constructor)
- 需要接受一个函数并执行,函数需要调用内部resolved和rejected方法
- 需要定义一个保存异步函数的私有属性
- 需要定义一个保存当前状态的私有属性
constructor(executor) {
// 构造函数,传入执行函数。
this.status = MyPromise.PENDING; // 设置初始状态
this.value = null;
this.callbacks = []; // 存储pending状态回调函数
try {
// 异常检测
executor(this.resolved.bind(this), this.rejected.bind(this)); // 执行函数
} catch (error) {
this.rejected(error) // 出错按rejected处理
}
}
resolved方法:执行成功的异步函数
resolved(value) {
// 成功的执行函数
if (this.status === MyPromise.PENDING) {
// 状态保护,仅处理pending状态
this.status = MyPromise.FULFILLED; // 改变状态为fulfilled
this.value = value;
this.callbacks.forEach(callback => {
// 遍历回调数组,执行pending状态下存入数组中成功的回调
callback.onFulfilled(this.value);
})
}
}
rejected方法:执行失败的异步函数
rejected(error) {
// 失败的执行函数
if (this.status === MyPromise.PENDING