乐趣区

实现Promise基本原理

let P = class {
constructor(callback) {
this.resolveSet = [];
this.rejectSet = [];
setTimeout(() => { **// 先把 then 的回调先 push 到数组,然后在调用该回调 **
callback(this.resolve.bind(this), this.reject.bind(this))
}, 0);
}

resolve(result) {
this.resolveSet.reduce((before, current,i) => {// 链式调用
if(i ===1){
return current(before(result))
}else{
return current(before)
}
})
}

reject(err) {}

then(callback) {
this.resolveSet.push(callback);
return this
}
catch (callback) {}
}
new P((resolve, reject) => {
return resolve({
result: ‘resolve’
})
}).then(data => {
return {
result: 1
}
}).then((x) => {
return {result:2}
}).then(x=>{
debugger
}),

一个简单是实现原理,resolve 方法中使用 reduce,为的是链式调用,首次遍历 callback 数组时,下标为 1,传入到首次的返回结果。如果有错请各位多多指点,勿喷,

退出移动版