1、什么是Promise
首先Promise是一个类,它是为了解决异步问题、恶魔金字塔、并发异步问题而诞生的。
在Promise类中需要传入一个executor(执行器),这个执行器默认会立即执行,Promise内部会提供两个方法resolve和reject,者两个方法可以更改Promise的状态。调用resolve触发成功里面传成功的内容,调用reject触发失败里面传失败的原因。
2、Promise的三个状态
Promise有三个状态:等待态(pending)、成功态(fulfilled)、失败态(rejected);当Promise是等待态的时候他可以变为成功态或失败态,变为成功态或失败态后Promise的状态不可再变化。失败的情况有两种调用reject和抛出异常。
3、Promise的then方法
每个Promise实例都要有一个then方法,then方法里面传了两个函数成功的回调(onfulfilled)和 失败的回调(onrejected)。
4、手写简易Promise
const PENDING = 'PENDING';
const RESOLVED = 'RESOLVED'; //成功
const REJECTED = 'REJECTED'; //失败
class Promise{
constructor(executor){
this.status = PENDING; //默认是等待态
this.value = undefined; //成功的内容
this.reason = undefined; //失败的原因
this.onResolvedCallbacks = []; //存放成功的回调函数
this.onRejectedCallbacks = []; //存放失败的回调函数
// 只有状态是等待态的时候才可以更改状态
let resolve = (value) => {
if(this.status === PENDING){
this.value = value;
this.status = RESOLVED;
// 需要让成功的方法依次执行
this.onResolvedCallbacks.forEach(fn=>fn());
}
};
let reject = (reason) => {
if(this.status === PENDING){
this.reason = reason;
this.status = REJECTED;
// 需要让失败的方法依次执行
this.onRejectedCallbacks.forEach(fn=>fn());
}
}
//执行executor 传入成功和失败
try{
executor(resolve, reject)
}catch(e){
// 如果内部出错直接将err手动调用reject方法向下传递
reject(e)
}
};
then(onfulfilled, onrejected){
if(this.status === RESOLVED){
onfulfilled(this.value);
};
if(this.status == REJECTED){
onrejected(this.reason);
};
// 当status为pending时,executor内部肯定有异步逻辑
// 用发布订阅模式实现异步逻辑
if(this.status === PENDING){
this.onResolvedCallbacks.push(()=>{
onfulfilled(this.value);
});
this.onRejectedCallbacks.push(()=>{
onrejected(this.reason);
})
}
}}
module.exports = Promise;