How to reduce the use of the wait keyword in async while waiting while maintaining execution order

async function foo() {
  await this.getAsync();
  await this.getAsyncTwo();
  await this.getAsyncThree();
  await this.getAsyncFour();
}

See how foo has several pending calls, is there a way to simplify this while maintaining the order of execution?

I would like to write something like

async function foo() {
  await 
   this.getAsync(), 
   this.getAsyncTwo(), 
   this.getAsyncThree(), 
   this.getAsyncFour();
}

or

async function foo() {
  await 
   this.getAsync() 
   .this.getAsyncTwo() 
   .this.getAsyncThree()
   .this.getAsyncFour();
}
+4
source share
2 answers

This guarantees the sequential execution order that you wish.


async function foo() {
  const functions = [this.getAsync, this.getAsyncTwo, ...];

  for (let func of functions) { 
    await func();
  }
}
+3
source

You can wait on Promise.all()

await Promise.all([this.getAsync(), this.getAsyncTwo(), /* etc */])
+1
source

Source: https://habr.com/ru/post/1674740/


All Articles