基本原理
1.通過構造方法生成一個promise對象,但是構造方法中傳入的方法不會立即調用
2.通過then給promise對象中的成功方法列表中添加方法,通過catch給promise中的失敗方法列表添加方法
3.初始狀態為pending,且變為fulfilled或rejected后不會再被改變
4.在添加完所有方法后執行構造函數中添加的方法,僅有構造函數中傳入的方法可以修改promise的執行狀態,后續then中添加的方法不會有resolve,reject的傳參
class PromiseA {
constructor(asyncFunc) {
this.handlerList = []
this.catchList = []
this.state = 'pending'
setTimeout(() => {
asyncFunc(this.resolve.bind(this),this.reject.bind(this))
});
return this
}
resolve() {
if (this.state !== 'pending') { // 保證promise狀態在改變后不會再被修改
return
}
this.state = 'fulfilled'
this.handlerList.forEach(element => { // 依次運行所有注冊在成功調用方法列表中的方法
element()
});
}
reject(err) {
if (this.state !== 'pending') { // 保證promise狀態在改變后不會再被修改
return
}
this.state = 'rejected'
this.catchList.forEach(element => { // 依次運行所有注冊在錯誤捕獲方法列表中的方法
element(err)
})
}
then(asyncFunc) {
this.handlerList.push(asyncFunc)
return this
}
catch(errFunc) {
this.catchList.push(errFunc)
}
}
new PromiseA((resolve, reject) => {
setTimeout(() => resolve(), 3000)
// reject('123')
reject()
})