Promise简单总结
1、Promise规范:https://promisesaplus.com/
2、Promise类的设计
// 两者的区别
class HYPromise{
}
function HPYromise(){
}
3、构造函数的规划
// 定义promise的三种状态
const PROMISE_STATUS_PENDING = "pending";
const PROMISE_STATUS_FULFILLED = "fulfilled";
const PROMISE_STATUS_REJECTED = "rejected";
// 工具函数:处理catch方法抛出异常
function execuFunctionWithCatchError(execuFn,value,resolve,reject){
try{
const result = execuFn(value);
resolve(result);
}catch(err){
reject(err);
}
}
class HYPromise{
constructor(executor){
this.status = PROMISE_STATUS_PENDING;
this.value = undefined;
this.reason = undefined;
this.onFulfilledFns = [];
this.onRejectedFns = [];
// 定义resolve回调函数
const resolve = (value) => {
if(this.status === PROMISE_STATUS_PENDING){
queueMicrotask(() => {
// 状态变化的话直接就结束,对于resolve/reject只执行其中一个就可以
if (this.status !== PROMISE_STATUS_PENDING) return
this.status = PROMISE_STATUS_FULFILLED;
this.value = value;
this.onFulfilledFns.forEach(fn => {
fn(this.value);
});
})
}
};
// 定义reject回调函数
const reject = (reason) => {
if(this.status === PROMISE_STATUS_REJECTED){
queueMicrotask(() => {
// 状态变化的话直接就结束,对于resolve/reject只执行其中一个就可以
if (this.status !== PROMISE_STATUS_PENDING) return
this.status = PROMISE_STATUS_REJECTED;
this.reason = reason;
this.onRejctedFns.forEach(fn => {
fn(this.reason);
})
})
}
};
// 链式调用
try{
executor(resolve,reject);
}catch(err){
reject(err);
}
}
then(onFulfilled,onRejected){
// 异常抛出给下一个reject进行处理
onRjected = onRejected || (err => {throw err!!!})
// 返回一个新的promise对象,符合链式调用
return new HYPromise((resolve,reject) => {
// 针对setTimeout类似情况,如果在then调用的时候,状态已经确定下来,并且onFulfilled存在值时
if(this.status === PROMISE_STATUS_FULFILLED && onFulfilled){
onFulfilled(this.value);
execuFunctionWithCatchError(onFulfilled,this.value,resolve,reject);
}
if(this.status === PROMISE_STATUS_REJECTED && onRejected){
onRejected(this.reason);
execuFunctionWithCatchError(onRejected,this.reason,resolve,reject);
}
// 状态未确定时,执行该代码,将成功回调和失败回调放到数组中
if(this.status === PROMISE_STATUS_PENDING){
if(onFulfilled) this.onFulfilledFns.push(() => {
execuFunctionWithCatchError(onFulfilled,this.value,resolve,reject);
});
if(onRejected) this.onRejectedFns.push(() => {
execuFunctionWithCatchError(onRejected,this.value,resolve,reject);
});
}
});
}
catch(onRejected){
return this.then(undefined,onRejected);
}
finally(onFinally){
this.then(() => {
onFinally();
},() => {
onFinally();
})
}
}
const promise = new HYPromise((resolve,reject) => {
resolve(111);
reject(222);
});
promise.then(res => {
console.log("res:",res);
},err => {
console.log("err:",err);
}).finally(() => {
console.log("finally");
})
promise.then(res => {
console.log("res2:",res);
},err => {
console.log("err2:",err);
})
setTimeout(() => {
promise.then(res => {
console.log("res3:",res);
},err => {
console.log("err3:",err);
})
},1000)
3、resolve、reject方法
const promise =