I have a class method that chains together other methods in the class, and also calls a method on another instance of the class:
class Thing {
doSomething(nextThing) {
return new Promise((resolve) =>
this.initialize()
.then(() => this.doA())
.then(() => {
nextThing.initialize(); // call initialize() on another instance
return this.doB();
})
.then(() => this.doC())
.then(resolve)
);
}
initialize() {
return new Promise((resolve) => {
// take a long time to do something
// ...
// ...
resolve();
});
}
doA() { return new Promise((resolve) => resolve()); }
doB() { return new Promise((resolve) => resolve()); }
doC() { return new Promise((resolve) => resolve()); }
}
const thing1 = new Thing();
const thing2 = new Thing();
thing1.doSomething(thing2);
Calling the function on the other class instance locks up the flow of the chain, however; this.doB()
and nextThing.initialize()
will run simultaneously (as desired), but this.doC()
won't run until nextThing.initialize()
has resolved.
What's the right way to make sure this flows as expected, with nextThing.initialize()
and this.doB()
starting simultaneously, and starting this.doC()
immediately after this.doB()
resolves? It's okay if nextThing.initialize()
resolves after this.doC()
.