【发布时间】: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 - 这没有意义。我已经更新了代码。我当时一定在想“试着抓住”。
-
还要避免该循环中的
Promiseconstructor antipattern!
标签: javascript node.js promise bluebird