所有承诺解决后返回

Return after all promises resolved

本文关键字:返回 解决 承诺      更新时间:2023-09-26

下面有一个代码示例,我想在所有承诺解决后从"main"函数返回 baz 变量。

exports.foo = function(bar) {
    var baz;
    // some kind of promises are here forming array of promises p
    // some of promises may change the baz variable
    Promise.all(p).then(() => {
      // returning expression for main function is here
      // return baz here // does not work
    });
    // return baz //cannot be done because it would be earlier than all the async promises are resolved
}
承诺在

主返回解决,因此返回 baz 的承诺:

exports.foo = function(bar) {
  var baz;
  return Promise.all(p).then(() => baz);
}
exports.foo(3).then(baz => console.log(baz)).catch(e => console.error(e));