实现一个简陋地Promise
程序员文章站
2022-07-03 09:32:26
...
简单实现地代码如下
class PromiseTest{
constructor(callBack){
this.successEventBus = [];
this.value = null;
this.failedEventBus = [];
const reslove = (successData) => {
this.value = successData;
this.successEventBus.forEach( cb => cb(this.value))
}
const reject = (failedData) => {
this.value = failedData;
this.failedEventBus.forEach( cb => cb(this.value))
}
callBack(reslove, reject)
}
then(cb){
this.successEventBus.push(cb)
}
catch(cb){
this.failedEventBus.push(cb)
}
}
使用如下
let cc = new PromiseTest((reslove, reject) => {
setTimeout(()=>{
reslove(1)
},10000)
})
cc.then(res => {
console.log(res, '+++')
})
上一篇: 【Promise】Promise基本使用
下一篇: 从实现一个Promise说起