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}) }
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)]); };
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})))
Keep Exploring 🛥️
Top comments (0)