3

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
}
jmoerdyk
  • 5,544
  • 7
  • 38
  • 49
olegzhermal
  • 799
  • 10
  • 26
  • 1
    foo() doesnt return anything. You have to return Promise.all.then and handle the promise in the caller method. – Himmet Avsar Mar 18 '16 at 15:34
  • It'd be best if the promise chain resolved to `baz` and keep on working within the promise chain. – MinusFour Mar 18 '16 at 15:35
  • Something tells me this is only because of pseudocode writing, but it is *very* crucial: Is it actually `return Promise.all(p).then(() => {`? Without the `return`, it's always going to come back undefined. – Katana314 Mar 18 '16 at 16:06
  • 2
    One important thing is, you cannot return value synchronously from a function which does asynchronous activity – thefourtheye Mar 18 '16 at 16:18
  • 1
    Just return a promise for `baz`! `return Promise.all(…).then(…);` – Bergi Mar 18 '16 at 18:43
  • What you are trying to do is not possible. – Kevin B Mar 18 '16 at 19:32

1 Answers1

3

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));
jib
  • 40,579
  • 17
  • 100
  • 158
  • 1
    ohhh gawd.. so simple but elegant. This whole javascript promise/async/wait is driving me a little crazy coming from the vanilla Java dev background. – apil.tamang Oct 19 '19 at 21:11