【问题标题】:JavaScript/Angular 1 - Promise.all to async-awaitJavaScript/Angular 1 - Promise.all 到 async-await
【发布时间】:2018-06-27 09:10:40
【问题描述】:

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

【问题讨论】:

  • 你想让 onInit 异步/等待吗?
  • @zabusa 是的,或者为此创建一个新方法
  • 你可以在onInit()中调用异步函数
  • @zabusa 如果我将逻辑移到新方法上?
  • (对于 AngularJS)你应该使用 $q.all() 而不是 Promise.all()

标签: javascript angularjs async-await ecmascript-2017


【解决方案1】:

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 函数总是返回一个承诺)

【讨论】:

    【解决方案2】:

    您可以使用 $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();
    });
    

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

      • 请注意语义上的细微差别,因为您不使用“all”组合符:如果仅拒绝contactTypesPromise,这仍会分配它不与“全部”组合器。
      • 好点 - 如果原来的“如果一个人炸了,它应该全部炸毁”错误处理是可取的,它可以用 try catch 重新创建。
      猜你喜欢
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 2018-05-09
      • 2018-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多