研究Promise時,想過本身模擬下這個異步機制,今天封裝了一套簡易代碼:app
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); } } } })();
線上代碼測試地址爲:
線上測試地址異步