诺言中的承诺没有依次使用

时间:2019-01-23 11:14:22

标签: javascript node.js promise bluebird

我在节点脚本中使用了Bluebird Promise库,但在理解代码执行顺序时遇到了麻烦。 我有一个使用.each方法的Promises数组,因此它们按顺序依次执行。在每个这些诺言中,我都有两个链接的诺言,但是第二个诺言并未按照我的期望执行。

如果我们采用以下代码,我会认为输出为0.0, 0.1, 0.2, 1.0, 1.1, 1.2 ... etc。但这似乎并非如此。它正在产生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);
});

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

2 个答案:

答案 0 :(得分:2)

问题在于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));
})();

答案 1 :(得分:0)

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

.each方法的第二个参数需要返回承诺,以便在那时执行。

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