【问题标题】:Node.js: Async function seems to not wait for resolve of Promise within for loopNode.js:异步函数似乎不等待 for 循环中 Promise 的解析
【发布时间】:2019-03-12 21:03:58
【问题描述】:

在第一个 await new Promise 执行后,For 循环结束,没有任何代码。如果我理解正确,每次迭代应该在Promise 被解析之前暂停2 秒,console.log 输出指定的字符串,并且迭代结束。我应该如何重写代码以使其按预期工作?

'use strict';

(async function () {
    for (let i = 0; i < 5; i++) {
        await new Promise(resolve => { setTimeout(() => { resolve }, 2000) });
        console.log('end of loop');
    }
})();

【问题讨论】:

  • 投票结束。问题是由错字引起的。 您忘记了调用resolve函数所需的()

标签: javascript node.js async-await es6-promise


【解决方案1】:

您需要在 setInterval 回调中调用 resolve 函数。

await new Promise(resolve => { setTimeout(() => { resolve() }, 2000) });

【讨论】:

  • setInterval -> setTimeout
【解决方案2】:

你可以这样写,

'use strict';

var wait2Sec = function (time = 2000) {
    return new Promise(function (resolve, reject) {
        setTimeout(() => { 
            resolve(); // <--- remamber to call the resolve function
        }, time)
    });
}

(async function () {
    for (let i = 0; i < 5; i++) {
        await wait2Sec();
        console.log('end of loop');
    }
})();

【讨论】:

    【解决方案3】:

    在您的 sn-p 中,setTimeout 将调用匿名函数,该函数将评估 resolve 作为表达式,它返回一个函数。您需要显式调用resolve() 或将其作为function 类型的第一个参数传递给setTimeout

    改变

    setTimeout(() => { resolve }, 2000)
    

    setTimeout(resolve, 2000)
    

    setTimeout(() => { resolve() }, 2000)
    

    【讨论】:

    • @Milan setTimeout 超时后调用第一个参数(函数),也可以指定参数如setTimeout(resolve, 2000, "promise will be resolved with this string")
    • 在任何一种情况下,似乎 OP 要么不知道它是需要调用的函数,要么只是创建了一个类型。正如 Quentin 建议的那样,这整个问答线程并没有给 Stack Overflow 社区增加太多内容。
    • @Milan 同意你的看法
    猜你喜欢
    • 2021-10-18
    • 1970-01-01
    • 2020-03-27
    • 2021-11-13
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    相关资源
    最近更新 更多