Ilja
Ilja

Reputation: 46479

Awaiting several promises in one async function

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.

Upvotes: 3

Views: 245

Answers (1)

sdgluck
sdgluck

Reputation: 27287

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')
  } 
}

Upvotes: 7

Related Questions