手写promise
/**
* 定义类的思路
* 分析功能
*/
class MyPromise {
// 创建一个变量存储Promise结果
_result;
// 创建一个变量记录promise状态
_state = 0; //pending0 fufilled1 rejected2
// 创建一个变量存储回调函数
_callbacks = [];
constructor(executor) {
// 接受一个执行器作为参数
executor(this._resolve.bind(this), this._reject.bind(this));
}
// 私有的resolve() es6中使用# 不使用箭头函数 在类中因严格模式 this=undefined 所以可以使用.bind()重新指定this 且这种情况下函
// 数在实例对象的原型下更省内存
_resolve(value) {
this._result = value;
// 禁止值被重复修改
if (this._state !== 0) return;
this._state = 1;
// 当resolve执行时说明数据进来了 调用 then的回调函数
queueMicrotask(() => {
// 调用callbacks中所有函数
this._callbacks.forEach((cb) => {
cb();
});
});
}
// 箭头函数形式
// _resolve=(value)=>{
// console.log(this);
// }
// 私有reject()
_reject(reason) {}
then(onFufilled, onRejected) {
return new MyPromise((resolve, reject) => {
if (this._state == 0) {
// 说明数据还没进入promise
// 将回调函数设置为callback
this._callbacks.push(() => {
resolve(onFufilled(this._result));
});
} else if (this._state == 1) {
// then的回调函数应放到微任务队列而不是直接调用
queueMicrotask(() => {
resolve(onFufilled(this._result));
});
}
});
}
}
const mp = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve("11");
}, 1000);
});
mp.then((result) => {
console.log(23, result);
return 11;
})
.then((result) => {
console.log(result);
return 33;
})
.then((result) => {
console.log(result);
});