我有点迷路了,我想我是在打“看不到树木的森林综合症”。
我是一个JS NooB,我正在尝试理解如何按顺序调用一组JS函数(返回promises)。我已经做了一些阅读,并决定考虑到我正在使用Node,我应该使用像bluebird这样的东西来管理promises。
我搞不懂的是为什么这段代码不能工作
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.我迷路了。
非常感谢你提前
发布于 2016-12-30 22:03:14
代码的最后一部分有一个意外的bug:
then(countdown(5, "Basic : Timer2") );这意味着countdown()的结果被用作回调函数。(直接执行倒计时功能)
相反,请使用
then(function(lastResult){ countdown(5, "Basic : Timer2") });变量lastResult将具有链中较早的promise的返回值。
https://stackoverflow.com/questions/41397403
复制相似问题