https://juejin.im/post/5d0da5c8e51d455ca0436271#heading-3
自定义实现及解析如下
class MyPromise {
constructor (fn) {
this.status = "pending";
this.value = "";
// 由于then是同步调用,因此无法拿到异步之后的状态
// 因此需要将异步cb暂存起来以实现异步的效果,拿到异步的value
this.fulfillArray = [];
this.rejectArray = [];
let resolveFn = (value) => {
console.log(value);
// setTimeout(() => { // 模拟异步
this.status = "fulfilled";
this.value = value;
this.fulfillArray.map((item) => {
item(value);
})
// }, 0);
}
let rejectFn = (result) => {
console.log(result);
// setTimeout(() => { // 模拟异步
this.status = "rejected";
this.value = result;
this.rejectArray.map((item) => {
item(result);
})
// }, 0)
}
fn(resolveFn, rejectFn);
}
then(resolveCb, rejectCb) { // 以同步的方式调用
console.log("111111")
return new MyPromise((resolve, reject) => {
this.fulfillArray.push(() => {
let x = resolveCb(this.value);
resolve(x);
});
this.rejectArray.push(() => {
let x = rejectCb(this.value);
reject(x);
});
})
}
catch(rejectCb) {
return this.then(null, rejectCb)
}
}
let p1 = new MyPromise((resolve, reject) => {
setTimeout(() => { // 异步请求
let ran = Math.random();
console.log("ran===", ran);
ran > 0.5 ? resolve(100) : reject(-100)
}, 0);
}).then((res) => {
console.log("res===", res);
return res;
}, (err) => {
console.log("err===", err);
return err;
}).then((res) => {
console.log("res2===", res);
return res;
}, (err) => {
console.log("err2===", err);
return err;
})
setTimeout(() => {
console.log(p1)
}, 10);
运行结果如下:
111111 // 可见then调用是以同步的形式
111111 // 第二个then调用
// 开始执行异步
ran=== 0.36985480393587333
// 异步结束之后调用cb
-100
err=== -100
// 第二个异步mypromise
-100
err2=== -100
-100
MyPromise {
status: 'rejected',
value: -100,
fulfillArray: [],
rejectArray: [] }
网友评论