我有点失落,我认为我击中了“不能看到树木综合征”。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())' –