所有承诺解决后返回

时间:2016-03-18 15:25:42

标签: javascript node.js return promise es6-promise

下面有一个代码示例,我希望在所有promises解决后从'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
}

1 个答案:

答案 0 :(得分:0)

承诺在主要返回后解析,所以返回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));