Assume a code block loads a module on demand like this:
let tbls = document.querySelectorAll("div.magic-table");
if(tbls) {
import('./magic-table.js')
.then(module => {
L.magictables = module.magictables;
tbls.forEach(o => {
L.magictables.init(o);
});
})
.catch(err => {
console.error("Unable to load magic-table.js: " + err.message);
});
}
Imagine that there are a few of those in sequence; they differ in what tag/class they search for, and what module they load, and perhaps some extra step in the initialization, but overall they are the same and they are independent.
Now assume you need to introduce a new block which may depend on other modules. I.e:
I know very little about javascript, and virtually nothing about async javascript, so I have no idea how this could be done. What I'm imagining is something like:
Before any of the module loading blocks, create an array called promises. Each time a module which is a dependency is actived, it creates a promise which it adds to the promises list. Once that module is done it "triggers" the promise (I have no idea how one does this, but conceptually):
let tbls = document.querySelectorAll("div.magic-table");
if(tbls) {
let promise = new MyMagicPromise();
promises.push(promise);
import('./magic-table.js')
.then(module => {
L.magictables = module.magictables;
tbls.forEach(o => {
L.magictables.init(o);
});
promise.trigger();
})
}
Just before the module which depends on other optional modules something like this is done to create a barrier at which all the previous modules must complete their initialization:
promises.forEach(p => {
await p;
});
Is there some out-of-the-box mechanism to accomplish this in javascript already? If not, would what I'm imagining work?
I can't put the dependent module loading into another block's then(), because the dependent block may depend on multiple other modules (if they are used).
Also: Plain javascript; no frameworks.
I dont really get you... but i guess i know what you want. You make your outer function async
(async () => {
let module1 = (await import("...")).default
let module2 = (await import("...")).default
})()
This is actually the basics how you import modules sequencial with async