為了更好地理解Promise如何在Javascript中工作,我決定自己嘗試一下并編寫基本的實(shí)現(xiàn)。基本上,我想實(shí)現(xiàn)以函數(shù)為參數(shù)的Promises對(duì)象(在我的代碼中稱為Aaa)。此函數(shù)可以調(diào)用resolve對(duì)承諾的解決,也可以拒絕reject。基本實(shí)現(xiàn)和用法如下。不知道第二個(gè)參數(shù)是否可以按照promise規(guī)范接受,但這就是我到目前為止所得到的。Aaa=function(f,pause) { console.log("ggg"); var t=this; this.f=f; this.thens=[]; this.resolve=function(g) { for(var i=0;i<t.thens.length;i++) { // try/catch to be used later for dealing with exceptions try { t.thens[i].f(g); t.thens[i].resolve(); } catch(ex) {} } }; // to be implemented later this.reject=function(g) {}; this.then=function(resolve,reject) { // i'm passing true for pause argument as we dont need to execute promise code just yet var nextPromise=new Aaa(resolve,true); this.thens.push(nextPromise); return nextPromise; } if(!pause) this.f(this.resolve,this.reject); }var aaa=new Aaa(function(resolve,reject) { console.log("aaa"); setTimeout(function() { console.log("fff"); resolve("good"); },2000); console.log("bbb");});因此,現(xiàn)在可以創(chuàng)建,調(diào)用和解決承諾。每個(gè)then方法將返回新的Aaa(承諾),因此可以將它們鏈接在一起。現(xiàn)在,下面的代碼使用上面創(chuàng)建的promise并鏈接then回調(diào)。每個(gè)then返回新的諾言,在這種情況下,它似乎可以正常工作:aaa.then(function(res) { console.log("ccc"); console.log(res);}).then(function(res) { console.log("ddd"); console.log(res);},function(rej) { console.log("eee"); console.log(rej);});我得到的輸出是:gggaaa bbb ggg ggg fff ccc good ddd undefined 如何最好地實(shí)施?
添加回答
舉報(bào)
0/150
提交
取消