Return after all promises resolved [duplicate]

為{幸葍}努か 提交于 2019-12-11 02:37:40

问题


Having a code sample below, I'd like to get baz variable returned from 'main' function after all promises resolved.

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:


Promises resolve after main returns, so return a promise of baz instead:

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


来源:https://stackoverflow.com/questions/36088230/return-after-all-promises-resolved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!