JavaScript / Node Promises:按顺序执行它们

我有点失落,我认为林打“不能看到木材的树木综合征”。

我是JS NooB和Im试图了解如何调用一组JS函数(它返回承诺)按顺序。 我已经做了一些阅读,并已决定给我使用节点我应该使用像蓝鸟的东西来pipe理承诺..

我无法解决的是为什么这段代码不起作用

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,'timer1')执行第一,然后,只有当timer1完成后,将timer2执行..

但是,当我运行这个我得到

 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(countdown(5, "Basic : Timer2") ); 

这意味着countdown()的结果被用作callback函数。 (倒计时function直接执行)

反而使用

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

variableslastResult将具有链中早期诺言的返回值。

 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!"); });