Construct object from multiple promises

Viewed 176

I want to construct an object from multiple promise results. The only way to do this is something like this:

const allPromises = await Promise.all(asyncResult1, asyncResult2);
allPromises.then([result1, result2] => {
  return {result1, result2};
})

A nicer way (especially when more data is being constructed) would be this, with the major drawback of the async requests happening one after the other.

const result = {
  result1: await asyncResult1(),
  result2: await asyncResult2(),
}

Is there a better way to construct my object with async data I am waiting for?

1 Answers

See my comment, it's a little unclear what asyncResult and asyncResult2 are, because your first code block uses them as though they were variables containing promises (presumably for things already in progress), but your second code block calls them as functions and uses the result (presumably a promise).

If they're variables containing promises

...for processes already underway, then there's no problem with awaiting them individually, since they're already underway:

const result = {
    result1: await asyncResult1, // Note these aren't function calls
    result2: await asyncResult2,
};

That won't make the second wait on the first, because they're both presumably already underway before this part of the code is reached.

If they're functions

...that you need to call, then yes, to call them both and use the results Promise.all is a good choice. Here's a tweak:

const result = await Promise.all([asyncResult1(), asyncResult2()])
                    .then(([result1, result2]) => ({result1, result2}));

One of the rare places where using then syntax in an async function isn't necessarily the wrong choice. :-) Alternately, just save the promises to variables and then use the first option above:

const ar1 = asyncResult1();
const ar2 = asyncResult2();
const result = {
    result1: await ar1,
    result2: await ar2,
};
Related