JavaScript/Node promise : Executing them in sequence

标签 javascript node.js

我有点迷茫,我想我遇到了“只见树木不见森林综合症”。

我是一个 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/

相关文章:

javascript - 修改每个div 彼此分开

javascript - 传递给回调函数的 "ui"对象的 jQuery UI 对象类型?

javascript - 如何使用 moment 获取重复日期

node.js - NodeJS Express - 分别处理 404(未找到)和 405(不允许的方法)

Javascript 检查窗口是否由脚本打开

javascript - 如何从我自己的谷歌地图中删除标记

javascript - 渲染后调用react componentDidMount执行

javascript - 在包含(文字连接)中使用文字与 Sequelize

node.js - 将对象传递给路由器

javascript - 在客户端 JavaScript 代码中重用 Node.js 中的 Web 模型