I have two async methods that are independent of each other that I would like to run simultaneously to save time. However, to continue with the following step, I need to wait for both the return values from the two methods. My code looks something like this:
public async methodOne(): Promise<MyObjectOne> {
... do something interesting
return one;
}
public async methodTwo(): Promise<MyObjectTwo> {
... do something interesting
return two;
}
public useVariables(one: MyObjectOne, two: MyObjectTwo) {
... do some useful work
}
public async runTogether(): Promise<void> {
let one: MyObjectOne;
let two: MyObjectTwo;
await Promise.all([this.methodOne(), this.methodTwo()])
.then((values: [MyObjectOne, MyObjectTwo]) => {
values.map((value: MyObjectOne | MyObjectTwo) => {
if (value instanceof MyObjectOne) {
one = value;
} else {
two = value;
}
});
})
.catch((error) => {
throw new Error('There was an error');
});
this.useVariables(one, two);
}
Based on my best understanding, by the time the program reaches the last line this.useVariables(one, two);
, either both the variables are set or an error has been thrown.
But the IDE is indicating on both variables that the Variable 'one/two' is used before being assigned
.
I can check for undefined just before using the two variables to get rid of the errors. But I'm wondering if this message is indicating that I've missed something. Or is it simply that the IDE does not recognizing that the variables are set? Alternatively, is there a better way to run the two methods simultaneously?