Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 443
Ilja Avatar asked Jan 19 '26 11:01

Ilja


1 Answers

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')
  } 
}
like image 165
sdgluck Avatar answered Jan 21 '26 23:01

sdgluck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!