Reputation: 55
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()?
Upvotes: 0
Views: 4783
Reputation: 665486
First simplify your code from that array push
ing 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)),
]);
Upvotes: 0
Reputation: 121
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)
Upvotes: 3
Reputation: 5566
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]);
Upvotes: 4