Mastering the art of utilizing async await efficiently

Currently, I am trying to save/update data in my Firestore document. I have successfully implemented this without any issues by using an async function. However, I must admit that I am not very familiar with async functions or promises.

I have provided my code below and my main question is: Am I implementing this function correctly? Is this the proper way to update/create using an async function?

Thank you in advance for your help!

Here is the excerpt from 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
}

}

Answer №1

It can be difficult to assess the correctness of something without clarity on its intended purpose.

Rather than catching an error only to immediately rethrow it, it may be more practical to let errors propagate naturally for the caller to manage.

Additionally, the statement below lacks coherence:

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

The then() method is typically used for handling successful outcomes, not errors.

Answer №2

Using async functions provides a cleaner and more readable syntax compared to traditional promise handling. Below is an example showcasing the difference between using async/await and promises:

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 versions achieve the same result as they both return a promise.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Understanding the concept of mutable properties in Typescript

Why can the property 'name' in the class 'PersonImpl' be reassigned even though it is not declared as read-only in the Person interface? interface Person { readonly name: string; } interface Greeting extends Person { greet( ...

Harness the power of Angular 2 on standard shared hosting services

Starting with AngularJS 2: Installed NodeJS Downloaded the initial project Ran it on Node Everything works perfectly! But now, how can I run it in a production environment on shared hosting (without Node and not on a VPS)? How can I open it in a browse ...

By utilizing a function provided within the context, React state will consistently have its original value

After passing functions from one component to its parent and then through context, updating the state works fine. However, there is an issue with accessing the data inside these functions. They continue to show as the initial data rather than the updated v ...

Issue with bootstrap modal new line character not functioning properly

Is there a correct way to insert a new line for content in a modal? I have this simple string: 'Please check the Apple and/or \nOrange Folder checkbox to start program.' I placed the '\n' newline character before "Orange," e ...

Creating an empty TypeScript variable with type FileList can be achieved by declaring the variable and initializing it with

After completing a coding test that required building a react app for uploading files using Typescript, I encountered a dilemma. Specifically, I needed to use the useState hook to store the uploaded file and set its default value. Typically, setting the de ...

Resolving Problems with Ion-Split-pane in the Latest Versions of Angular and Ionic

There seems to be a perplexing issue with the ion-split-pane element that I just can't wrap my head around. Once I remove the split-pane element, the router-outlet functions perfectly fine. The navigation is displayed after a successful login. The on ...

Tips on displaying the entire text when hovering over it

I'm facing an issue with a select element that retrieves options from an API. The problem is that some options are too large for the text box and get cut off, making them hard to read for users. <div class="form-group my-4"> <lab ...

Getting the value of the chosen option from one component and passing it to another component in Angular 8

How can I pass the selected option value from the login component to the home component without using local storage? When an option is selected in the login component, I want that value to be displayed in the home component. Below is the code snippet: Lo ...

Removing an object from a JSON array based on checkbox selection in Angular 4

0: CategoryId: "31b7a227-9fda-4d14-8e1f-1dee5beeccb4" Code: "GMA0300" Description: "PA-5215: Renamed" Enabled: true Favorite: false Id: "26cfdb68-ef69-4df0-b4dc-5b9c6501b0dd" InstrumentType: null Moniker: "1GMA0300" Name: "Celiac Disease Panel (tTG IgG, tT ...

Extension for VSCode: Retrieve previous and current versions of a file

My current project involves creating a VSCode extension that needs to access the current open file and the same file from the previous git revision/commit. This is essentially what happens when you click the open changes button in vscode. https://i.stack. ...

"String representation" compared to the method toString()

Currently, I am in the process of writing unit tests using jasmine. During this process, I encountered an issue with the following code snippet: let arg0: string = http.put.calls.argsFor(0) as string; if(arg0.search(...) This resulted in an error stating ...

Angular Update Component on Input ChangeEnsuring that the component is automatically

<div class=" card-body"> <div class="row"> <div class=" font-icon-list col-lg-2 col-md-3 col-sm-4 col-xs-6 col-xs-6" routerLinkActive="active" *ngFor="let subject of subjects"> <div class=" fon ...

VSCode prioritizes importing files while disregarding any symbolic links in order to delve deeper into nested node

I'm encountering a problem with VSCode and TypeScript related to auto imports. Our application includes a service known as Manager, which relies on certain functions imported from a private npm package called Helpers. Both Manager and Helpers make us ...

Creating a dynamic user interface in Angular 6 that successfully tracks changes without reliance on the parent

As I delve into the world of Angular, I am faced with a challenge in creating a reusable component that will be bundled into an npm module. The issue lies in the UI change detection aspect. In order for the component to function properly, the application ...

Need help restarting a timer I've built in Angular with just a click?

I am in the process of developing a compact application that will help me keep track of my activities within a specific time frame. Once I input an activity into a field and click "OK," it should be added to a list. My current challenge lies in resetting ...

Can you explain the significance of <any> when used before a Typescript class constructor parameter?

Currently, I am immersing myself in the Angular - Testing documentation. While going through the section on testing asynchronous services (specifically HTTP services), I came across a class constructor containing an <any> right before the passed argu ...

Determine if a condition is met in Firebase Observable using scan() and return the

Within Firebase, I have objects for articles structured like this: articles UNIQUE_KEY title: 'Some title' validUntil: '2017-09-29T21:00:00.000Z' UNIQUE_KEY title: 'Other title' validUntil: '2017-10-29T21:00:00 ...

Learn how to trigger an HTTP exception after a failed command in a saga with NestJS CQRS

Currently utilizing the NestJS CQRS pattern to handle interactions between User and UserProfile entities within my system. The setup consists of an API Gateway NestJS server along with dedicated NestJS servers for each microservice (User, UserProfile, etc. ...

Determining the appropriate scenarios for using declare module and declare namespace

Recently, I came across a repository where I was exploring the structure of TypeScript projects. One interesting thing I found was their typings file: /** * react-native-extensions.d.ts * * Copyright (c) Microsoft Corporation. All rights reserved. * Li ...

The incorrect output directory path being generated by Typescript

While working on a series of projects with the same tsconfig.json files, I've encountered a strange issue in one of them. I have "outDir": "./lib", The expected results (.js, .d.ts) from src should be placed in the lib directory just like in the o ...