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

时间:2016-12-30 13:53:46

标签: javascript node.js

我有点失落,我觉得我打得“看不见木头为树木综合症”。

我是一个JS NooB,我试图理解如何按顺序调用一组JS函数(返回promises)。我做了一些阅读,并决定,鉴于我使用Node我应该使用像bluebird这样的东西来管理承诺..

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

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.

我迷路了......

非常感谢提前

3 个答案:

答案 0 :(得分:4)

代码的最后一部分有一个意想不到的错误:

    then(countdown(5, "Basic : Timer2") );

这意味着countdown()的结果用作回调函数。 (倒计时功能直接执行)

改为使用

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

变量lastResult将具有链中先前承诺的返回值。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

您可以尝试此项目:https://github.com/LvChengbin/sequence

Sequence.all( [
    () => countdown( 5, 'Basic : Timer1' ),
    () => countdown( 5, 'Basic : Timer2' )
] )

您可以使用Sequence.all方法的第二个参数在每两步之间指定interval

您可以阅读其文档以获取更多信息。