I have two async functions that need to run in series.
FunctionA needs to be completed in all nested functions before FunctionB is run.
Nested functions pass a variable to the next function.
Functions firstA2 and secondB2 do not return a value.
Is there a way accomplish it without using timeout?
FunctionA()
FunctionB()
FunctionA: function (){
---
----
first_A1(X)
}
first_A1:function(X){
----
----
first_A2(Y)}
}
first_A2(Y){
-----
-----
}
FunctionB: function (){
---
----
second_B1(Z)
}
second_B1:function(Z){
----
----
second_B2(G)}
}
second_B2(G){
-----
-----
}
CodePudding user response:
See promise concurrency for various ways to achieve what you are after.
Promise.all() Fulfills when all of the promises fulfill; rejects when any of the promises rejects.
Promise.allSettled() Fulfills when all promises settle.
Promise.any() Fulfills when any of the promises fulfills; rejects when all of the promises reject.
Promise.race() Settles when any of the promises settles. In other words, fulfills when any of the promises fulfills; rejects when any of the promises rejects.
CodePudding user response:
This is basic async/await. You can learn more on MDN or any other JavaScript documentation of your choice. Of course, you can do it with Promises as well, but I personally prefer async/await syntax (it's much more simple and readable for my taste).
Anyway, if I understood correctly what you are trying to accomplish, here's how to do it:
async function functionA() {
let result = await firstA1();
// since your requirements mentioned that "nested functions are passing variable to next functions", I've assumed that you wanted to process the result somehow. You can really, pass anything to firstA2 here
await firstA2(result);
// since your example lists two calls, here's the second call
await firstA2(result);
return result;
}
// Same goes for function B and its "nested" functions
async function functionB() {
let result = await secondB1();
await secondB2(result);
await secondB2(result);
return result;
}
// Now to run both in series... functionB will not be run until functionA and all its nested functions completes.
async function runFunctionsInSeries() {
let resultA = await functionA();
let resultB = await functionB();
}