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

£可爱£侵袭症+ 提交于 2021-01-23 07:47:45

问题


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?


回答1:


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.




回答2:


There is no replacement for Promise.all in async/await syntax. It still works on promises, it's sugar for then calls only.

So use

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

(this works a bit different than your original code which did not return anything from $onInit, not sure whether that was intentional - an async function always returns a promise)




回答3:


You can use $q.all() for the alternate of your need as per the given example as shown below,

$q.all([this.ReferenceService.getMultipleReferences(this.AgentReferences), this.ContactService.getContactTypes()]).then(function(result) {
    this.referencesPromise = result[0];
    this.contactTypesPromise = result[1];
    this.stateParams = this.$state.params;
    return this.setContactSteps();
});


来源:https://stackoverflow.com/questions/48318869/javascript-angular-1-promise-all-to-async-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!