Promise 本质上是一个有限状态机 发表于 2018-09-05 | 本文总阅读量 次 状态机是什么? promise本质上是一个有限状态机,将下列代码粘贴到任何一个支持ES6的浏览器下都可以正常使用,与本来的promise使用方法没有区别,下面是具体的代码。代码很短,但能完整诠释Promise原理。12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091//promise的本质就是一个有限状态机class Promise2 { constructor(fn) { let me=this; me.__queue = []; me.__status=''; me.__success_res=null; me.__error_res=null; fn&&fn(value=>{me.resolve(value)}, reason=>{me.reject(reason)}); } resolve(...args){ this.__status = 'success'; this.__success_res = args; this.__queue.forEach(json=>{ json.resolve(...args); }); } reject(...args){ this.__status = 'error'; this.__success_res = args; this.__queue.forEach(json=>{ json.reject(...args); }); } then(resolve, reject) { if (this.__status == 'success') { resolve(...this.__success_res); } else if (this.__status == "error") { reject(...this.__error_res); } else { this.__queue.push({ resolve, reject }); } }}Promise2.all=function(args){ let res=[]; let p= new Promise2(); let i=0; next(); function next(){ let me=this; args[i].then(function(re){ res.push(re); i++; if (i==args.length) { p.resolve(res); }else{ next(); } },p.reject); } return p;}//test1let p=new Promise2(function(resolve,reject){ setTimeout(function(){ resolve(12); },500);});p.then(function(params){ alert(params);},function(params){ alert("失败");});//test2let p1=new Promise2();setTimeout(function(){ p1.resolve(13);},500);p1.then(num=>{ alert(num);});//test3let p2=new Promise2();setTimeout(function(){ p2.resolve(12);},500);let p3=new Promise2();setTimeout(function(){ p3.resolve(13);},500);Promise2.all([p2,p3]).then(function(args){ alert(args[0]+args[1]);}); 坚持原创技术分享,您的支持将鼓励我继续创作! 打赏 微信支付 支付宝