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

See how foo has multiple await calls, is there a way of simplyfing this while keeping execution order?

I wish it was possible 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();
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Cisum Inas
  • 11,552
  • 11
  • 40
  • 55
  • 4
    I fear it's already in it's simplest form. Depending on what you plan to do with the results of those awaits, using the array method below might save you a line or two for the cost of more characters per line of code. – Shilly Apr 13 '17 at 11:39
  • Can you post your actual code, please, so that we may judge based on the purpose of those calls? – Bergi Apr 13 '17 at 12:11
  • The actual code contains 4 calls in one function scope (backbone js model). Async await have already made life alot easier compared to the nested .then() => {} calls.. – Cisum Inas Apr 13 '17 at 13:49
  • 2
    `async/await` is part of ES2017, not ES7. – Felix Kling Apr 14 '17 at 04:37
  • @felixKling fair enough :) – Cisum Inas Apr 14 '17 at 12:05
  • 1
    None of your functions return anything? Less isn't always more. – jib Apr 15 '17 at 04:49
  • @jib in reality they change attribute data on an backbone model, so yeah stuff happen that I need to await for.. – Cisum Inas Apr 18 '17 at 14:11
  • I mean once you return something e.g. `let result = await this.getAsync();` then your semantic optimization breaks down. – jib Apr 18 '17 at 14:59
  • @jib sure It would break down in some cases, however in my case I am working on attributes directly on the object (an backbone model). This means in the case at hand it would not break down.. – Cisum Inas Apr 19 '17 at 10:11

2 Answers2

3

This will guarantee the sequential execution order you wished for.


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

  for (let func of functions) { 
    await func();
  }
}
Lyubomir
  • 19,615
  • 6
  • 55
  • 69
1

You can await on a Promise.all()

await Promise.all([this.getAsync(), this.getAsyncTwo(), /* etc */])
Dom Vinyard
  • 2,038
  • 1
  • 23
  • 36