3

I am trying to take advantage of es7 async functions i.e.

async function stepVerifyIdentity(nextState, replace, callback) {
    const val1 = await promise1('Param1')
    const val2 = await promise2('Param2')
    const val3 = await promise3('Param3')
    if (!val1 && (!val2 || !val3)) {
        console.log('Do something')
    } 
}

here all promise* functions make an ajax call and return either true or false if passed parameters are satisfied by ajax response, I believe I can't use 3 awaits in a row, hence need a way to wait for all of these calls to return their values somehow.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Ilja
  • 44,142
  • 92
  • 275
  • 498
  • I had a similar problem. Maybe this helps you. In my case I was using jquery promises though. http://stackoverflow.com/questions/37658721/strange-unexpected-jquery-promise-reject-behaviour – Mayday Sep 07 '16 at 14:00
  • 2
    @Mayday `Promise.all` looks promising (no pun intended) – Ilja Sep 07 '16 at 14:01
  • 1
    I'm not 100% familiar with es7, but promise.all ? – Shilly Sep 07 '16 at 14:02
  • 2
    "*I believe I can't use 3 awaits in a row*" - of course you can, what do you think is the problem with that? (Though you [may not want it](http://stackoverflow.com/q/24193595/1048572)) – Bergi Sep 07 '16 at 14:02

1 Answers1

7

You can use await as many times as you like, so your example would do what you want.

However, maybe you would consider Promise.all prettier:

async function stepVerifyIdentity(nextState, replace, callback) {
  const [ val1, val2, val3 ] = await Promise.all([
    promise1('Param1'),
    promise2('Param2'),
    promise3('Param3')
  ])

  if (!val1 && (!val2 || !val3)) {
    console.log('Do something')
  } 
}
sdgluck
  • 24,894
  • 8
  • 75
  • 90
  • 4
    this also has the benefit that all three requests are done in parallel, not one after another. – Thomas Sep 07 '16 at 14:20