Skip to content
Advertisement

Await functions but do them synchrony, then call the last function

So I am working with Vue, Node and typescript. I am fetching data that all my other functions are needing, so getDataForFunction123() needs an await and its fine.

Then I have 3 functions that is fetching different stuff, not depending on each other. But all answers is used by the last function updateAfterFunction123IsDone(). But when I have it like now, we need to wait synchrony for function 1, 2 and 3. It takes a lot of time. I want to make function 1, 2 and 3 to just do there stuff at the same time but also want to know when all 3 is done and then call updateAfterFunction123IsDone().

Here is the code:

async initData () {
  await this.getDataForFunction123();

  await this.function1();
  await this.function2();
  await this.function3();

  this.updateAfterFunction123IsDone();
}

I don’t think that an Promise.all() will solve this issue? Because it is also doing the function in a order and not in the same time? Right? That will not save me time, but save me some error handling?

Advertisement

Answer

Promise.all fires once all of its promises are resolved. So run all of your functions function1, function2, function3 immediately, without await, and then proceed once their promises are resolved:

async initData () {
  await this.getDataForFunction123();

  const p1 = this.function1();
  const p2 = this.function2();
  const p3 = this.function3();

  await Promise.all([p1, p2, p3]);
  this.updateAfterFunction123IsDone();
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement