How to make every service wait for the services it needs to be ready?
You're on the right track. The reason you're seeing duplicates is that home calls init for B and C, and B inits A, and C inits B, so you end up with
home -> B -> A
home -> C -> B -> A
Notice that A and B will get initialized twice. If the classes really have this dependency, then add a side-effect to the init process the class knows it's done. Something like:
asnyc Load() {
if (this.wasLoaded) return Promise.resolve();
await this.otherService.Load();
this.wasLoaded = true;
}
One "side-effect" of the load might be that some instance data on the object is getting set. The presence of that data might be a good flag for whether Load needs to execute.
The other thing to fix is that you've successfully removed the async calls from the constructors of service A, B, C, but your home
class calls its (async) Load()
method from the constructor. Remove that, too.
Stylistically, the most modern syntax is presented in your home
class. It's a style thing, but I'd copy that syntax (mark methods that use await
as being async
and use await
instead of then()
), to your other classes.
Lastly, in the async/await
style, errors are caught with try/catch
blocks, as in...
// in class A
async Load() {
if (this.dataWeGetFromB) return Promise.resolve();
try {
this.dataWeGetFromB = await this.BService.Load();
} catch (err) {
// handle err
}
}