JavaScript/Angular 1-Promise.all异步等待 [英] JavaScript/Angular 1 - Promise.all to async-await

查看:79
本文介绍了JavaScript/Angular 1-Promise.all异步等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 referencesPromise contactTypesPromise $ onInit()中的两个变量中为Web服务分配了两个调用(我可以创建一个新方法为此,如果需要的话)

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

他对async-await的选择是什么?

What is his alternative with async-await?

推荐答案

假设您仍然希望您的方法同时运行,则无需进行太多更改:

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.

这篇关于JavaScript/Angular 1-Promise.all异步等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆