2016-12-30 79 views
1

我有點失落,我認爲我擊中了「不能看到樹木綜合徵」。JavaScript/Node Promises:按順序執行它們

Im a JS NooB和我試圖瞭解如何調用一組JS函數(它返回承諾)按順序。香港專業教育學院做了一些研讀,並已決定使用即時通訊節點我應該使用類似藍鳥管理承諾給予..

我不能工作了什麼是爲什麼這段代碼不工作

var Promise = require("bluebird"); 
// My Promise enabled function from oReily Safari book 
function countdown(seconds, timername) { 
    return new Promise(function (resolve, reject) { 
     console.log('Countdown : Starting Countdown ' + timername); 
     for (let i = seconds; i >= 0; i--) { 
      setTimeout(function() { 
       if (i > 0) 
        console.log(timername + ' ' + i + '...'); 
       else 
       { 
        console.log('countdown '+timername+' now=='+i+' resolving!'); 
        resolve(console.log("Countdown : timename="+timername+" ended")); 
       } 
      }, (seconds - i) * 1000); 
     } 
    }); 
} 

/*Basic test of promise */ 
/* when this is run I expected countdown(5, 'Basic : Timer1') to execute and then when **resolved** THEN countdown(5, "Basic Timer2") to execute. 
*however what I see is both timers executing at the same time.. 
*/ 

console.log('Basic : Countdown promise test'); 
countdown(5, 'Basic : Timer1'). 
     then(function() 
     { 
      /*Success */ 
      console.log("Basic : Ended Successfully"); 
     }). 
     then(countdown(5, "Basic : Timer2") 
       ); 

當我跑這我期待倒計時(5,「定時器1」)執行第一,然後,只有當定時器1完成後,將定時器得到執行..

然而,當我運行此我得到

Basic : Countdown promise test 
Countdown : Starting Countdown Basic : Timer1 
Countdown : Starting Countdown Basic : Timer2 
Basic : Timer1 5... 
Basic : Timer2 5... 
Basic : Timer1 4... 
Basic : Timer2 4... 
Basic : Timer1 3... 
Basic : Timer2 3... 
Basic : Timer1 2... 
Basic : Timer2 2... 
Basic : Timer1 1... 
Basic : Timer2 1... 
countdown Basic : Timer1 now==0 resolving! 
Countdown : timename=Basic : Timer1 ended 
countdown Basic : Timer2 now==0 resolving! 
Countdown : timename=Basic : Timer2 ended 
Basic : Ended Successfully 
Done. 

林失去了..

很多感謝

+0

你有一個小小的錯字。 'then(countdow' should be'then(x => countdown())' –

回答

4

代碼的最後一部分有一個意外的錯誤:

then(countdown(5, "Basic : Timer2")); 

這意味着倒計時的結果()作爲回調函數。 (直接執行倒計時功能)

改用

then(function(lastResult){ countdown(5, "Basic : Timer2") }); 

可變lastResult將具有從該鏈中的較早承諾返回值。

+0

謝謝!特意感謝你解釋爲什麼。我沒有意識到參數「then」是一個回調函數,與函數調用本身.. – italianknows

1
console.log('Basic : Countdown promise test'); 
countdown(5, 'Basic : Timer1'). 
     then(function() 
      { 
       /*Success */ 
       console.log("Basic : Ended Successfully"); 
       return countdown(5, "Basic : Timer2"); 
      }). 
      then(function(){ 
       console.log("Finish!"); 
      }); 
0

你可以試試這個項目:https://github.com/LvChengbin/sequence

Sequence.all([ 
    () => countdown(5, 'Basic : Timer1'), 
    () => countdown(5, 'Basic : Timer2') 
]) 

你也可以使用Sequence.all方法的第二個參數指定兩者interval每一個步驟。

您可以閱讀其文檔以獲取更多信息。