0

I have an array arr, I want to loop for each element of it. In the loop, I call two fxns A() and then B(), What I want is loop will run parallel but for each element fxn A must run first then fxn B.

what i am doing is it :

[1,2,3].forEach(async(i)=>{
await A(i);//which call API & console & returns iA 
await B(i);//which call API & console & returns iB  
console.log('A & B Completed for '+ i) 
 }  )

//Desired Result

1A
1B
A & B Completed for 1
3A //due to parallelism
3B
A & B Completed for 3
2A
2B
A & B Completed for 2

Is it write or any other good way, please help.

ParagDineshGupta
  • 210
  • 2
  • 10

1 Answers1

0

What I want is loop will run parallel but for each element fxn A must run first then fxn B.

What you have will do that. The .forEach() loop itself will not wait for the await because .forEach() is not promise aware. So, the .forEach() loop will just run to completion, starting each of your loop iterations (in order) so they will all be "in-flight" at the same time. They will get started in order, but while running in flight at the same time, they can complete in any order (that is determined by the target server).

But, the way you're doing it like this, you don't have any way of communicating outside the loop for either errors or results or even completion.

For that reason, it is generally better (when you want to run things in parallel) to collect an array of promises and monitor its completion with Promise.all(). That will give you all three things you're missing:

  1. Notification of completion
  2. Proper error handling
  3. Collection of results in order

You could do that like this:

let promises = [1,2,3].map(async(i) => {
    let resultA = await A(i);//which call API & console & returns iA 
    let resultB = await B(i);//which call API & console & returns iB  
    console.log('A & B Completed for '+ i)
    return someValue; 
});

Promise.all(promises).then(results => { 
    console.log(results);
}).catch(err => {
    console.log(err);
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979