Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript/Angular 1 - Promise.all to async-await

I assign two calls to the web service in two variables in referencesPromise and contactTypesPromise $onInit() (I can create a new method for that, if needed)

$onInit() {
  const referencesPromise = this.ReferenceService.getMultipleReferences(this.AgentReferences)
  const contactTypesPromise = this.ContactService.getContactTypes()
  Promise.all([referencesPromise, contactTypesPromise]).then((responses) => {
    this.references = responses[0]
    this.contactTypes = responses[1]
    const stateParams = this.$state.params
    return this.setContactSteps()
  })
}

What is his alternative with async-await?

like image 742
Mouad Ennaciri Avatar asked Dec 30 '25 19:12

Mouad Ennaciri


1 Answers

Assuming you still want your methods to run concurrently there aren't too many changes to make:

async $onInit() {
  const referencesPromise = this.ReferenceService.getMultipleReferences(this.AgentReferences);
  const contactTypesPromise = this.ContactService.getContactTypes();

  this.references = await referencesPromise;
  this.contactTypes = await contactTypesPromise;
  const stateParams = this.$state.params;
  return this.setContactSteps();
}

Note how the initial calls are the same, we still want to capture the promises as we want both requests to run at the same time.

like image 79
UncleDave Avatar answered Jan 02 '26 08:01

UncleDave



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!