Jay Joshi
Jay Joshi

Reputation: 55

Writing multiple map functions in Promise.all()

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

Answers (3)

Bergi
Bergi

Reputation: 665486

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)),
]);

Upvotes: 0

Isuru Lakruwan
Isuru Lakruwan

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

IceMetalPunk
IceMetalPunk

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

Related Questions