Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Async Task inside Loop in Javascript
Bijish O B
Bijish O B

Posted on • Edited on

     

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})
Enter fullscreen modeExit fullscreen mode

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)})
Enter fullscreen modeExit fullscreen mode

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)))}
Enter fullscreen modeExit fullscreen mode

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})
Enter fullscreen modeExit fullscreen mode

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
peerreynders profile image
peerreynders
  • Joined
• Edited on• Edited

we can confirm the completion by resolving the promise by passingsomeData.

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 withPromise.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 callmyAsyncLoop 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.

unknown tweet media content
Jeff Whelpley profile image
Jeff Whelpley
@jeffwhelpley
twitter logo
Uh, 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
Twitter reply actionTwitter retweet actionTwitter like action
CollapseExpand
 
bijishjs profile image
Bijish O B
Software Engineer

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.

CollapseExpand
 
itsfz1 profile image
Fahim Zada
A software engineer who loves web development <3. Available for hire.
  • Location
    Nowshera, Pakistan
  • Education
    COMSATS Abbottabad
  • Work
    Freelancer
  • 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)})()
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
bijishjs profile image
Bijish O B
Software Engineer

Thank you for the crisp code demonstration. It gave me insights on using inline async function blocks. I want to clarify that I wrote thetask 2 - async comment as an abstraction for an awaiting database record existing check operation. I wish you a good day.

CollapseExpand
 
bijishjs profile image
Bijish O B
Software Engineer

Thank you for your valuable feedback. 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.

CollapseExpand
 
bijishjs profile image
Bijish O B
Software Engineer

I want to clarify that I wrote the// task 2 - async comment as an abstraction for an awaiting database record existing check operation.

CollapseExpand
 
devdufutur profile image
Rudy Nappée
French freelance dev
  • Location
    France
  • Work
    Lead dev at Niort
  • Joined

No need to declare async function if you never await anything

CollapseExpand
 
bijishjs profile image
Bijish O B
Software Engineer

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.

CollapseExpand
 
devdufutur profile image
Rudy Nappée
French freelance dev
  • Location
    France
  • Work
    Lead dev at Niort
  • Joined

I mean here :

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

The first async is useless because you return a promise and on the second I think you should await myAsyncIteration(item).

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Engineer
  • Location
    india
  • Joined

More fromBijish O B

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp