javascript模拟原生Promise语法
文章目录
研究Promise时,想过自己模拟下这个异步机制,今天封装了一套简易代码:
let Pms=null;
(function () {
function execFn(pms,type,data) {
let {[type+'Arr']:arr,status}=pms;
if (status != "pending" ) return;
arr.forEach((fn,index)=>{
fn.call(pms, data);
});
pms.status= type == "suc"? "fulfilled":"rejected";
pms.args=data;
}
Pms=class{
constructor(callBack){
this.status="pending";
this.sucArr=[];
this.errorArr=[];
this.args="";
callBack.apply(null, [execFn.bind(null, this,'suc'),execFn.bind(null, this,'error')]);
}
then(sucFn,errorFn){
this.sucArr.push(sucFn);
if (this.status == "fulfilled"){
sucFn.call(this, this.args);
}
if (typeof errorFn != "undefined"){
this.catch(errorFn);
}
}
catch(errorFn){
this.errorArr.push(errorFn);
if (this.status == "rejected"){
errorFn.call(this, this.args);
}
}
}
})();
线上代码测试地址为:
线上测试地址
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论