代码之家  ›  专栏  ›  技术社区  ›  Mouad Ennaciri

JavaScript/Angular 1-承诺。全部异步等待

  •  3
  • Mouad Ennaciri  · 技术社区  · 7 年前

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

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

    3 回复  |  直到 7 年前
        1
  •  3
  •   UncleDave    7 年前

    假设您仍希望方法同时运行,则不会有太多更改:

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

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

        2
  •  0
  •   Bergi    7 年前

    没有替代品 Promise.all 在里面 async / await 语法。它仍在履行承诺,这是糖 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 ,不确定这是否是故意的 异步 函数始终返回承诺)

        3
  •  -1
  •   Immanuel Kirubaharan    7 年前

    根据下面给出的示例,您可以使用$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();
    });