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:
- Notification of completion
- Proper error handling
- 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);
});