Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 14, 2022 02:41 pm GMT

Async Task inside Loop in Javascript

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 named myAsyncIteration which returns a promise. Inside the promise we perform the asynchronous task and we can confirm the completion by resolving the promise by passing someData

const myAsyncIteration = (item) =>    new Promise(async (resolve, reject) => {        //  task 1 - normal        //  task 2 - async        return resolve(someData)    })

In the second block, inside myAsyncLoop we map over every instance in myIterable to myAsyncIteration that returns a promise.

If there are 'n' instances inside myIterable then 'n' promises will be returned. This is wrapped with Promise.all which will ensure all the promises are executed and will contain the data which was resolved from the promises.

const myAsyncLoop = async () => {    return Promise.all(myIterable.map(async (item) =>        myAsyncIteration(item)    ))}

In the third block, we call myAsyncLoop which returns an array of data sent after resolving each promise. It means 'n' number of someData contributes to arrayOfSomeData.

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.


Original Link: https://dev.to/bijishjs/async-task-inside-loop-in-javascript-30io

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To