pingeyeg
pingeyeg

Reputation: 680

How to make multiple async await calls

I'm trying to build an object based on the responses from multiple promises, but I'm noticed where only the first promise is actually being worked on while the second is being ignored. What is the best practice to make this work?

if (goldenListKeys[0].name === 'date') {
  const date = moment('07-01-2019', 'YYYY-MM-DD').format('MM/DD/YYYY');
  _.assign(tmpObj, { inputData: { [goldenListKeys[0].name]: date } });
  try {
    await this.plansApi
      .compileFields({ tmpObj, carrier, benefitQuery })
      .catch(error => {
        value = error.response['invalid-selection'];
        console.log(`One: ${value}`);
      });
  } catch (err) {}
}
if (goldenListKeys[1].name === 'state') {
  console.log('Here');
  _.assign(tmpObj, {
    inputData: { ...tmpObj, [goldenListKeys[1].name]: 'NC' },
  });
  try {
    await this.plansApi
      .compileFields({ tmpObj, carrier, benefitQuery })
      .catch(error => {
        value = error.response['invalid-selection'];
        _.assign(goldenListKeys, { filler: value });
        console.log(`Two: ${value}`);
      });
  } catch (err) {}
}

Upvotes: 1

Views: 260

Answers (1)

Michael Sorensen
Michael Sorensen

Reputation: 2124

It appears that you missed one of the fundamental features of async/await.

An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.

The key part being is that the execution inside the function call is paused. So your next if statement won't be considered until after the first promise has resolved.

from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

This is usually where I like to use the Promise.all function MDN Link

This is how I would modify your code (I know it doesn't use async/await but, it should accomplish your goal)

function yourFunction(){

    let myPromiseArray = [];

    if (goldenListKeys[0].name === 'date') {

        const date = moment('07-01-2019', 'YYYY-MM-DD').format('MM/DD/YYYY');

        _.assign(tmpObj, { inputData: { [goldenListKeys[0].name]: date } });

        myPromiseArray.push(his.plansApi
            .compileFields({ tmpObj, carrier, benefitQuery }))
    }

    if (goldenListKeys[1].name === 'state') {

        _.assign(tmpObj, {
            inputData: { ...tmpObj, [goldenListKeys[1].name]: 'NC' },
        });

        myPromiseArray.push(this.plansApi
            .compileFields({ tmpObj, carrier, benefitQuery }))

    }

    Promise.all(myPromiseArray).then((resultArray)=>{
        //do something with results
    }).catch(errorArray => {
        //handle Errors
    })
}

Upvotes: 1

Related Questions