I need to run two (or more) lines of code in sequence in vanilla javascript.
Each invokes calls to routines (aka top level functions, which have a purpose of performing procedural steps rather than calculating a result). These in turn call multiple others.
function fMasterProcedure() {
fSubProcedure1();
fSubProcedure2();
... etc
}
Suppose the code for fSubProcedure1() is as follows (for this illustration):
function fSubProcedure1() {
fSubSubProcedure1_1(); // Normal
fSubSubProcedure1_2(); // Async
fSubSubProcedure1_3(); // Normal
fSubSubProcedure1_4(); // Async
fSubSubProcedure1_5(); // Normal
}
This is literally the same question as here how to run sequence functions in javascript, although the answers provided there do not show how to do it, and there have been syntax updates in the years since in relation to promises and asynchronous functions.
These days the answer seems to be promises and async/await... or is it just callbacks without using promises?
I have read many descriptions and tutorials on promises, including here.
However, I end up with code like this:
function fMasterProcedure() {
return (new Promise(function(resolve, reject) {
fSubProcedure1();
setTimeout(function () {
resolve();
}, 0);
})).then(function(result) {
fSubProcedure2();
});
}
As you can see, it adds 400% more lines unnecessarily and still doesn't work reliably.
Is there a more efficient way to write this, or a more appropriate way?
(The requirement is to run fSubProcedure2
after fSubProcedure1
(and any of its child processes) are completed in full. I am trying to move from "that's not how JS works" to "here's how to make JS achieve that requirement").
I'm trying to get the good understanding so I can apply it to a whole project approach - there are many examples within, of each.