简体   繁体   English

如何正确使用异步等待

[英]How to use async await properly

i am trying to save/update some data into my firestore document.I have implemented it successfully with out any problem.To save data i am using an async function.But i am not much familiar with async functions or promises. 我正在尝试将一些数据保存/更新到我的Firestore文档中。我已经成功实现了它,没有任何问题。要保存数据,我使用的是异步功能。但是我对异步功能或Promise不太熟悉。 i have posting my code below and my question is, am i implementing the function properly or not? 我在下面发布了我的代码,我的问题是,我是否正确实现了该功能? Is this the correct way to implement updation/creation using async function.? 这是使用异步功能实现更新/创建的正确方法吗?

Thanks in advance 提前致谢

Here is my code; 这是我的代码;

edit_menu.ts 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 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
}

} }

Without knowing what exactly it's supposed to do, it's not really easy to say whether or not it's correct. 在不知道它到底应该做什么的情况下,很难说出它是否正确。

I will say that it's not really meaningful to catch an error, then immediately rethrow it. 我会说,捕获错误并立即将其重新抛出是没有意义的。 Just let it throw on its own and make the caller deal with it. 只是让它自己抛出并使调用者处理它。

Also, this doesn't make sense: 另外,这没有任何意义:

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

then() is for processing succesful results, not handling errors. then()用于处理成功的结果,而不是处理错误。

Async function is just a different syntax. 异步函数只是一种不同的语法。 Here is the code without async/await. 这是没有异步/等待的代码。

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

with async/await 与异步/等待

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

Both functions return a promise. 这两个函数都返回一个承诺。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM