I am initializing my JS application by calling a number of methods asynchronously loading ressources, each of them depending of the previous ones. My intuitive solution is to nest the calls in callback functions (cba, cbb, cbc, cbd), beeing called from the inner of LoadA, LoadB, LoadC, LoadD respectively after these (LoadA, LoadB, LoadC, LoadD) were successfully completed:
app.LoadA( function cba() {
app.LoadB( function cbb() {
....
app.LoadC( function cbc() {
...
app.LoadD( function cbd() {
...
} );
} );
} );
} );
LoadA( cb )
{
let url = '.........'; // just an url
let req = new XMLHttpRequest();
req.open('GET', url, true);
req.responseType = 'arraybuffer';
let lh = this;
req.onload = function ol(event)
{
let arrayBuffer = req.response;
let loadedObject = Convert( arrayBuffer, ......... );
cb( loadedObject ); // call, if successed!
}
req.send(null);
}
....
LoadA returns without loading the object, so LoadB has to wait until LoadA's embedded onload function calls the callback cb and so on.
I don't like this nesting solution, as it is hard to overview and to maintain.
My question is: is there an other (focused on the "happy path", nicer, shorter, less confusing, easier to understand and maintain) possibility to achieve the same result?