【问题标题】:Promises within a promise not in sequence using each承诺中的承诺不按顺序使用每个
【发布时间】:2019-06-16 23:14:30
【问题描述】:

我在节点脚本中使用 Bluebird Promise 库,但我无法理解代码的执行顺序。 我有一组 Promises,我正在使用 .each 方法,因此它们按顺序依次执行。在每个承诺中,我都有两个链式承诺,但第二个承诺没有按照我期望的顺序执行。

如果我们采用以下代码,我会认为输出是0.0, 0.1, 0.2, 1.0, 1.1, 1.2 ...等。但这似乎并非如此。它正在产生0.0, 0.1, 1.0, 1.1, 0.2, 1.2 ...等。

function subPromise1(index)
{
    return new Promise(function (resolve, reject) {
        console.log(String(index) + ".1");
        resolve(index);
    });
}

function subPromise2(index)
{
    return new Promise(function (resolve, reject) {
        console.log(String(index) + ".2");
        resolve(index);
    });
}

var promiseArray = [];
for (var index = 0; index < 2; index++) {
    promiseArray.push(new Promise(function (resolve, reject) {
        console.log(String(index)+".0");
        subPromise1(index).then(subPromise2).then(function (result) {
            resolve(result);
        });
    }));
}

Promise.each(promiseArray, function (index) {
    console.log("Completed " + index);
}).then(function (result) {
    console.log(result);
    process.exit(0);
});

我会认为主要的“每个”承诺需要在执行数组中的下一个承诺之前解决? 任何有助于理解该问题的帮助将不胜感激。

【问题讨论】:

  • 我建议看看那个 for 循环。 Promise.each 应该是连续的,但 for 循环不保证是连续的。
  • .catch(function (err) { reject(err); }); 没有意义。
  • 谢谢Bergi - 这没有意义。我已经更新了代码。我当时一定在想“试着抓住”。
  • 还要避免该循环中的Promise constructor antipattern!

标签: javascript node.js promise bluebird


【解决方案1】:

问题在于 for 循环并在此循环内调用 promise。循环不会等待承诺完全解决。如果您希望使用 async/await,则可以使用以下代码获得预期的输出。

let result = [];
let indexes = [0, 1];
(async () => {
  for (let index of indexes) {
    console.log(String(index) + ".0");
    const r1 = await subPromise1(index);
    const r2 = await subPromise2(r1);
    result.push(r2);
  }

  console.log(JSON.stringify(result));
})();

【讨论】:

  • 如果你在循环中使用await,你不应该将promise 推到结果中,也不要使用Promise.each。直接收集期待值就行了!
  • 谢谢,好多了:-)
【解决方案2】:

在我最初的想法中,我假设 .each 正在执行承诺,因为它正在迭代数组,但事实并非如此。它在创建它们时在 for loop 中进行。

.each 方法的第二个参数需要返回 Promise 才能执行。

Promise.each(
    [ 0,1 ],
    function (index) {
        return new Promise(function (resolve, reject) {
            subPromise1(index).then(subPromise2).then(function (result) {
                console.log("Completed " + index);
                resolve(result);
            });
        })
    })
    .then(function (result) {
        console.log(result);
        process.exit(0);
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-16
    • 2016-11-23
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多