Skip to content Skip to sidebar Skip to footer

How To Synchronize An Async Map Function In Javascript

I have a async map function but want it to execute synchronously because I need the output of the first statement to be used within the same loop. But the map runs asynchronously e

Solution 1:

The modelVarients.map(async () => >...) converts all the elements into Promises, which means they all start executing. Then the Promise.all() collects them and waits for all of them, that's why you can use this structure to wait for the map to finish. This is parallel processing.

What you need is sequential processing, which you can do with a reduce, like this:

await modelVarients.reduce(async (memo, varient) => {
    await memo;
    // all the other things
}, Promise.resolve())

reduce is similar to map in a sense that it creates a Promise for all the elements in the array, but there is a current value that is passed from one element to the other. In this case, it is the Promise.resolve() for the first one, the result of the first for the second, and so on. With the await memo you can wait for the previous result.

With reduce, the last element will wait for the previous one, which waits for the previous one, and so on, so there is no need for a Promise.all.

I've written articles about how map and reduce works with async functions, they will help you see the big picture.


Solution 2:

looks like You should chain Your promises, not running then in parallel with Promise.all


Post a Comment for "How To Synchronize An Async Map Function In Javascript"