【问题标题】:How to use async await properly如何正确使用异步等待
【发布时间】:2019-03-03 14:45:54
【问题描述】:

我正在尝试将一些数据保存/更新到我的 firestore 文档中。我已成功实现它,没有任何问题。要保存数据,我正在使用异步函数。但我对异步函数或承诺不太熟悉。 我在下面发布了我的代码,我的问题是,我是否正确实现了该功能?这是使用异步函数实现更新/创建的正确方法吗?

提前致谢

这是我的代码;

edit_menu.ts

 async onSaveClick() {
try {
  this.modifyService.
    updateLocationWiseMenuData(this.data.id, this.valueArray)
    .then(error => {
      console.log(error);
    }).catch(eror => {
      console.log(eror)
    })
}
catch (error) {
  throw error
}

}

service.ts

  async updateLocationWiseMenuData(id: string, array: any[]) {
try {

  if (id && array.length) {
    for (const i of array) {
      if (i.defaultPrice) {
        await this.afs.collection(`Locations/${id}/menuList`).doc(`${i.id}`).update({
          defaultPrice: i.defaultPrice
        })
      }
      if (i.hasOwnProperty('isAvailable')) {
        await this.afs.collection(`Locations/${id}/menuList`).doc(`${i.id}`).update({
          isAvailable: i.isAvailable
        })
      }
    }
  }
}
catch (error) {
  throw error
}

}

【问题讨论】:

    标签: typescript google-cloud-firestore angular6


    【解决方案1】:

    异步函数只是一种不同的语法。这是没有 async/await 的代码。

    onSaveClick() {
      return this.modifyService.updateLocationWiseMenuData(this.data.id, this.valueArray)
        .then(success => {
          console.log(success);
        }).catch(error => {
          console.log(error)
        });
    }
    

    使用异步/等待

    async onSaveClick() {
      try {
        const success = await this.modifyService.updateLocationWiseMenuData(this.data.id, this.valueArray);
        console.log(success);
      } catch(error) {
        console.log(error)
      }
    }
    

    两个函数都返回一个承诺。

    【讨论】:

    • 谢谢你的重播。你能告诉我异步函数和普通函数的确切区别吗?
    • 除了语法没有区别。
    【解决方案2】:

    在不知道它到底应该做什么的情况下,很难说它是否正确。

    我会说捕获错误并没有真正意义,然后立即重新抛出它。让它自己抛出,让调用者处理它。

    另外,这没有意义:

    .then(error => {
      console.log(error);
    })
    

    then() 用于处理成功的结果,而不是处理错误。

    【讨论】:

    • Stevension,感谢您的快速回放,我知道 then() 正在处理成功的结果。我认为异步函数是处理承诺的更好方法;根据我的代码,edit_menu() 不需要是异步函数,只有 updateLocationWiseMenu() 需要是异步函数;如果我的结论不正确,请纠正它
    猜你喜欢
    • 2020-09-10
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    相关资源
    最近更新 更多