简体   繁体   中英

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. 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

 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
}

}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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