我有點失落,我認爲我擊中了「不能看到樹木綜合徵」。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.
林失去了..
很多感謝
你有一個小小的錯字。 'then(countdow' should be'then(x => countdown())' –