
In a project, I had a situation to perform an asynchronous task inside a loop. I majorly used the map method to do looping tasks.
myIterable.map((item)=>{// task 1 - normal// task 2 - async})
But the map method does not natively support async tasks, when something is made asynchronous inside the map method it returns some 'pending promises'.
[ Promise{ <pending> },... ]
To make the map method asynchronous I wrapped it with the concept of promises.
The logic is split into three code blocks.
In the first block, we have a function namedmyAsyncIteration
which returns a promise. Inside the promise we perform the asynchronous task and we can confirm the completion by resolving the promise by passingsomeData
constmyAsyncIteration=(item)=>newPromise(async(resolve,reject)=>{// task 1 - normal// task 2 - asyncreturnresolve(someData)})
In the second block, insidemyAsyncLoop
we map over every instance inmyIterable
tomyAsyncIteration
that returns a promise.
If there are 'n' instances insidemyIterable
then 'n' promises will be returned. This is wrapped withPromise.all
which will ensure all the promises are executed and will contain the data which was resolved from the promises.
constmyAsyncLoop=async()=>{returnPromise.all(myIterable.map(async(item)=>myAsyncIteration(item)))}
In the third block, we callmyAsyncLoop
which returns an array of data sent after resolving each promise. It means 'n' number ofsomeData
contributes toarrayOfSomeData
.
myAsyncLoop().then((arrayOfSomeData)=>{console.log(arrayOfSomeData)// perform the other work})
In this way, I performed async tasks inside the map method. This is my first blog post, please share your thoughts and if there are any better methods please mention them also.
Thank you.
Top comments(9)

we can confirm the completion by resolving the promise by passing
someData
.
Perhaps I'm misunderstanding something.
An async task should already be or return a promise (thenable) so wrapping it is unnecessary.
It's synchronous tasks that need to be wrapped in a promise with anexecutor.
This is wrapped with
Promise.all
which will ensure all the promises are executed.
If you wantall to be settled perhaps you should be usingPromise.allSettled()
instead as thePromise.all()
promise will reject on the first rejection.
In the third block, we call
myAsyncLoop
which returns an array of data sent after resolving each promise.
It returnsa promise that will resolve to the array of data (as your later code demonstrates) unless one of them rejects.
Thank you.
OK, that's the happy path.
How are you dealing with potential rejection?
Edge case: Be careful about promises the may never resolve: e.g. browser autoplay policies can lead to promises fromplay()
/resume()
that never resolve.
Jeff Whelpley@jeffwhelpleyUh, wat?
Crazy to see browser devs OK with a standard web API returning a promise that may never resolve.
I always wonder with things like this how many hours of developer productivity are lost because we stupidly assume a promise will always resolve.
bugs.chromium.org/p/chromium/iss…18:33 PM - 12 Aug 2022

Thank you for your detailed valuable feedback. It gave me more insights into issues that would cause due to the improper handling of promises. I will go through the points you mentioned and correct my code. I want to clarify that I wrote the// task 2 - async
comment as an abstraction for an awaiting database record existing check operation. I wish you a good day.

- LocationNowshera, Pakistan
- EducationCOMSATS Abbottabad
- WorkFreelancer
- Joined
Using map for async tasks here I'm fetching 10 todos from json place holder.
(async()=>{//creating 10 values of array filled with indexesconstpromiseList=[...newArray(10).keys()].map(async(_,index)=>{constresponse=awaitfetch(`https://jsonplaceholder.typicode.com/todos/${index+1}`)returnawaitresponse.json()})constresolvedList=awaitPromise.all(promiseList)console.log(resolvedList)})()

No need to declare async function if you never await anything

Thank you for your valuable feedback. I want to clarify that I wrote the// task 2 - async
comment as an abstraction for an awaiting database record existing check operation. I wish you a good day.

I mean here :
const myAsyncLoop = async () => { return Promise.all(myIterable.map(async (item) => myAsyncIteration(item) ))}
The first async is useless because you return a promise and on the second I think you should await myAsyncIteration(item).
For further actions, you may consider blocking this person and/orreporting abuse