我有点迷茫,我想我遇到了“只见树木不见森林综合症”。
我是一个 JS 新手,我正在尝试了解如何按顺序调用一组 JS 函数(返回 promises)。我做了一些阅读,并决定鉴于我使用的是 Node,我应该使用像 bluebird 这样的东西来管理 promise 。
我无法解决的是为什么这段代码不起作用
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")
);
当我运行它时,我希望 countdown(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() 的结果用作回调函数。 (直接执行倒计时功能)
改为使用
then(function(lastResult){ countdown(5, "Basic : Timer2") });
变量 lastResult
将具有链中较早 promise 的返回值。
关于JavaScript/Node promise : Executing them in sequence,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41397403/