DEV Community

Cover image for Weekly Awesome JS KT Part-2: Promise.all() vs multiple awaits
Ishan Mishra
Ishan Mishra

Posted on

Weekly Awesome JS KT Part-2: Promise.all() vs multiple awaits

Imagine you have a case where you want to retrieve some information about a list of users, and for each user you have to hit the endpoint and await a promise, how will you do it? I came across a similar problem(I am giving a simplified version of the problem I came across not the full code), and the approach I took was something like this:

First I created a async function which handles all the logic of updating and getting a particular user from its id

const updateUser = async ({userId}:{userId:string})=>{

await updateUserDetails(userId)

}

userIds = [....]

// loop for each userId and update it
for(const id of userIds)
{
 await updateUser({userId: id})
}
Enter fullscreen mode Exit fullscreen mode

But there is a problem with this code, let me explain with a more simplified example:

const test1 = async () => {
  const delay1 = await Promise.delay(600); 
  const delay2 = await Promise.delay(600); 
  const delay3 = await Promise.delay(600); 
};

const test2 = async () => {
  await Promise.all([
  Promise.delay(600), 
  Promise.delay(600), 
  Promise.delay(600)]);
};

Enter fullscreen mode Exit fullscreen mode

Here test1 takes almost ~1800ms to run since it runs sync each promises whereas test2 takes ~600ms to runs since it runs all promises in parallel

So a faster version of the code snippet one would be something like this:

const updateUser = async ({userId}:{userId:string})=>{

await updateUserDetails(userId)

}

userIds = [....]

await Promise.all(userIds.map((userId)=>updateUser({userId})))

Enter fullscreen mode Exit fullscreen mode

Keep Exploring 🛥️


https://stackoverflow.com/questions/45285129/any-difference-between-await-promise-all-and-multiple-await

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay