1.实现简单的promise功能
let p1 = new Promise1((res,rej)=>{
//实现异步任务
setTimeout(()=>{
res('成功了');
},3000)
// rej('失败了');
});
p1.then((res)=>{
console.log('第一次输出:',res);
},(rej)=>{
console.log(rej);
})
p1.then((res)=>{
console.log('第二次输出:',res);
},(rej)=>{
console.log(rej);
})
手动实现promise的以上功能,即对异步任务的监听。
以下是编码实现:
class Promise1 {
_status = 'pending';
//存放成功时的回调函数集合
onResolve = [];
//存放失败时的回调函数集合
onReject = [];
constructor(fn){
this.fulfilled = this.fulfilled.bind(this);
this.rejected = this.rejected.bind(this);
fn(this.fulfilled,this.rejected);
}
fulfilled(val){
//手动实现异步 发布成功消息
setTimeout(()=>{
if (this._status = 'pending'){
this._status = 'fulfill';
this.onResolve.forEach((item)=>{
item(val);
})
}
})
}
rejected(val){
//手动实现异步 发布失败消息
setTimeout(()=>{
if (this._status = 'pending'){
this._status = 'reject';
this.onReject.forEach((item)=>{
item(val);
})
}
})
}
then(res,rej){
//订阅事件
this.onResolve.push(res);
this.onReject.push(rej);
}
}
结果展示:3秒钟之后显示:
代码解析:在代码执行的过程中,先执行构造函数,传入两个函数resolve 和 reject,resolve 和 reject 函数在执行的过程中,因为是异步函数,被放在任务队列中,等待同步任务执行结束后再执行。因此先执行then方法,类比于发布订阅模式,then方法其实就是订阅者将自己(失败和成功)的回调函数存放在函数列表中,then方法执行结束后,此时执行异步操作,如果是成功,就遍历成功回调函数中的所有函数,并将数据传给他们,失败就遍历失败回调函数集合中的所有函数。