Passing Variables Through a Promise Chain

Tim Scott picture Tim Scott · Jan 27, 2017 · Viewed 12.1k times · Source

Is there a better way to do this?

let foo;
return functionA().then(result => {
  foo = result;
  return functionB();
}).then(bar => {
  return functionC(foo, bar);
});

Notice that the result of functionA is required input to functionC. Using a variable outside the promise scope works fine, but it feels kinda icky. Is there a clean idiomatic way to do this?

Please note that I do not have the opportunity to change the API of any of the functions I am calling.

Answer

Alexander Staroselsky picture Alexander Staroselsky · Jan 27, 2017

You could try using Promise.all() which you can pass an array of promises and it provides an array of responses within the then() callback when all promises passed in have resolved. You can access those array values to pass into functionC:

Promise.all([functionA, functionB]).then(values => functionC(values[0], values[1]));

Might be a little cleaner (without nesting) as it doesn't look like the response from functionA needs to be passed into functionB.

Otherwise, nesting would look like:

return functionA().then(foo => {
    return functionB().then(bar => {
        return functionC(foo, bar);
    });
});