function resolvePromise(promise2, x, resolve, reject) {
//判断x的类型,来处理promise是成功还是失败
//所有的promise都遵循这个规范,不同的人写的promise可能会混用
//尽量考虑周全,要考虑别人promise可能出错的情况
if(promise2 === x){
return reject(new Error("循环引用"));
}
if (typeof x === "function" || (typeof x === "object" && x !== null)) {
let called;
try {
let then = x.then;
if (typeof then === "function") {
//成功状态
then.call(x,y=>{
if (called) return;
called = true;
resolvePromise(promise2, y, resolve, reject);//递归调用,把所有resolve返回值传到then中
},r=>{
if(called) return;
called = true;
reject(r); //让promise变成
})
}else{
//x 是一个普通的函数,没有then方法
resolve(x)
}
}catch (e) {
if (called) return;
called = true;
reject(e);
}
}else{
//常量
resolve(x);
}
}
class Promise {
//实例化的时候转入一个回掉函数实行器,实行resolve和reject
constructor(executor){
this.value; //为什么成功
this.reason; //为什么是失败
this.status = "pending"; //状态 成功态和失败态不能同时存在
深入源码理解promise
最新推荐文章于 2023-02-23 09:53:52 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)