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

标签 javascript angularjs async-await ecmascript-2017

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

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

关于JavaScript/Angular 1 - Promise.all 到异步等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48318869/

相关文章:

javascript - 按类查找 Angular 元素的最佳方法是什么?

javascript - 将自定义类添加到 Angular 选择的容器

javascript - Promise 已解决,但代码在等待中停止

javascript - karma angularjs 方法测试中的 console.log

javascript - 可以使用带有 textarea 行值的 CSS 转换吗?

javascript - Bootstrap-表自定义搜索

javascript - angularjs - 指令模板未以正确的方式编译

performance - 异步和等待 : are they bad?

javascript - 如何应对 async/await hell ?

java - 从另一个窗口关闭所有子窗口浏览器