0

I've two working blocks of Promise.all() in a single method. I want to combine these two Promise.all() into one. The individual Promise.all() includes a map function that performs an asynchronous task. Example:

let obj1 = [], obj2 = [];
await Promise.all(container1.map(async (item)=>{
   obj1.push(await dbCall(item));
}))

await Promise.all(container2.map(async (item)=>{
   obj2.push(await dbCall(item));
}))

The above piece of block populates the dB as well as the local containers (obj1,obj2)

Whereas, including these two map functions in single Promise.all([map1,map2]) does not populate the local containers (obj1,obj2) (dB gets updated as expected)

How can I include two map functions in single Promise.all()?

3 Answers 3

4

Keep in mind that Array.map returns a new array, in this case an array of Promises since async/await functions always return Promises. So your example of passing [map1, map2] will be a two-dimensional array; it'll be an array of arrays of Promises. Something like this:

[[Promise1, Promise2, Promise3, ...], [Promise4, Promise5, Promise6...]]

The Promise.all function expects an array of Promises, not an array of arrays of Promises, hence it fails. You just need to pass it the correct structure of array, which you can do with Array.concat (for ES5 syntax) or the spread operator (for ES6 syntax).

Promise.all(map1.concat(map2));
// OR
Promise.all([...map1, ...map2]);
Sign up to request clarification or add additional context in comments.

1 Comment

Completely missed the two-dimensional array from multiple maps. Merging above map functions did help out to await for all the promises to complete. Thanks! @IceMetalPunk !
3

you first try to merge the two arrays and then

let obj = [];
container1.foreach((item)=>{
    obj.push(dbCall(item));
})
container2.foreach((item)=>{
    obj.push(dbCall(item));
})

await Promise.all(obj)

1 Comment

Hey Isuru, thanks for taking your time out. Over here, the dbCalls are asynchronous. Hence, I'll need to add in the await to every dbCall I make. Unfortunately, we cannot have asynchronous functions as callbacks for 'foreach' . So the above piece of code won't retrieve the value given out by the dbCall. But the merging of maps does make sense. Thanks Isuru :)
0

First simplify your code from that array pushing to

const obj1 = await Promise.all(container1.map(dbCall));
const obj2 = await Promise.all(container2.map(dbCall));

Then, to run both of them concurrently, add another Promise.all around them:

const [obj1, obj2] = await Promise.all([
  Promise.all(container1.map(dbCall)),
  Promise.all(container2.map(dbCall)),
]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.