JavaScript/Angular 1 - Promise.all 异步等待

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

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

$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 的替代方案是什么?

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

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

请注意初始调用是如何相同的,我们仍然希望捕获承诺,因为我们希望同时向 运行 发出两个请求。

您可以根据下面给出的示例使用 $q.all() 来替代您的需要,

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

async/await 语法中的 Promise.all 没有替代品。它仍然适用于承诺,它只是 then 调用的糖分。

所以使用

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

(这与您的原始代码有点不同,原始代码没有 return 来自 $onInit 的任何内容,不确定这是否是故意的 - async 函数总是 returns一个承诺)