How to designate a try / catch block as asynchronous in TypeScript / JavaScript?

I am facing an issue where the code is not entering the catch block in case of an error,

try {
    this.doSomething();
} catch (error) {
    console.error(error);
}

This problem occurs when "doSomething" returns a promise or runs asynchronous code.

doSomething() {
    return new Promise<void>((resolve, reject) => {
        this.MySubscription = this.myService.fetchUserDataFromDB().subscribe({
            next: (val: any) => {
                this.userData = val

                resolve()
            }, error: (error) => {
                let uiErrorMsg = 'Failed to fetch user data';
                let consoleErrorMsg = 'Error occurred when calling backend API fetchUserDataFromDB';
                if (error instanceof HttpErrorResponse) {
                    consoleErrorMsg += ` | Status: ${error.status} ${error.statusText} | URL: ${error.url}`;
                }
                const consoleError = new Error(consoleErrorMsg);

                if(error?.status != 401) {
                    const data = [{ title: 'Alert', message: [uiErrorMsg] }, { okButtonTitle: 'Close' }]
                    let dialogRef: any = this.dialog.open(ConfirmationModalComponent, {data});
                    // await firstValueFrom(dialogRef.afterClosed())
                }

                reject(consoleError);
            }
        })
    })
}

In some instances, I need to call this.doSomething() without waiting for it to finish, while in other cases I do need to wait. In those situations, I use the keyword await.

await this.doSomething();

There is a way to handle errors from a promise without awaiting for it, using a different syntax:

this.doSomething().catch(error => {
    console.error(error);
});

When I need to wait for it to finish, I use try/catch with "await." However, when I don't require it to finish, I have to use ".catch()" instead of try/catch to catch the errors.

I wonder if there are any plans to enable an async try block so that we can use try/catch syntax in both scenarios, rather than having two different approaches and maintaining consistency with other programming languages that follow standard try/catch behavior?

Perhaps something like

try async {
    this.doSomething()
} catch (error) {
    console.error(error)
}

and

try {
    await this.doSomething()
} catch (error) {
    console.error(error)
}

respectively?

Fortunately, my try/catch was primarily for error message handling presentation. However, I can see how this could be frustrating for someone expecting the catch block to execute regardless of whether they used "await" or not when invoking their function.

Is there a way to make a try/catch asynchronous, or should we continue using both .catch() syntax and try/catch syntax?

(I am working with TypeScript 4.9.5, rxjs 7.8.1)

Answer №1

It seems like the reason for avoiding using await is to prevent the rest of the code block from waiting for doSomething() to finish.

My suggestion is to always use await instead of .then()/.catch(), and utilize an async IIFE:

(async () => {
  try {
    await this.doSomething()
  } catch (error) {
    console.error(error)
  }
})()
// ... remaining code will continue running without waiting for `doSomething()` 
to complete

By doing this, the synchronous part of the doSomething() function will start executing right away, and when encountering an await within doSomething(), the original code block will proceed without pausing for doSomething() to finish.

You can simplify it by avoiding the IIFE in this manner:

async doSomething2() {
  try {
    await this.doSomething()
  } catch (error) {
    console.error(error)
  }
}

this.doSomething2()
// ... code will run without waiting for `doSomething()` to complete

If your main goal is logging errors to the console, you could create a helper function like so:

async function backgroundExec(f) {
  try {
    await f()
  } catch (error) {
    console.error(error)
  }
}

// ... later on:

backgroundExec(() => this.doSomething())

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

Show different JSON data based on the existence of another key in Javascript

Having recently started learning JavaScript, I attempted the code below but couldn't quite get it to work. Despite consulting various resources, I still wasn't successful. Desired Output: To check if AUTO damage is present in the data. If so, re ...

Unable to access a function from a different controller within an AngularJS Ionic framework application

How can I trigger or call the callkhs function in the LihatKhsController from the KhsController? function KhsController($scope, $rootScope){ $scope.$emit('callkhs', {param:'test'}); } I am attempting to retrieve parameter values ...

Select a hyperlink to access the corresponding tab

I've been playing around with bootstrap and AngularJS. I placed nav-tabs inside a modal-window and have it open when clicking on a link. However, I want the appropriate tab to open directly upon click. For example, if I click on "travel", I want the t ...

Bring in a JavaScript file to a Read-Evaluate-Print-Loop (

Currently experimenting on Windows 10 TP build 9926 with nodejs, I am attempting to import a JavaScript file into an active session of nodejs that is operating in the Windows command prompt. This will allow me to call functions from the imported script dir ...

Having trouble sending an HTTPS request in NodeJS only to receive an HTTP response instead

As I develop my website using NodeJS and deploy it on Heroku, I encountered an issue upon opening the website. Here is the problem at hand: When looking at the main source file of my web application: app.get('/', (req, res) => { var data ...

Designating a certain function to a designated button

On my page, I have three different forms with submit buttons in each. There is a code that is supposed to change the value of a button in a specific form when clicked. However, whenever I click on any submit button, all the values in the buttons of the v ...

Guide on presenting an image retrieved from a database with ajax

I am currently developing a straightforward mobile application that utilizes a database to store various types of content, including images. I have implemented ajax requests to retrieve this information and display it within the app. However, I am encounte ...

Encountering an "Invalid parameter: redirect_uri" error in Keycloak while manually refreshing the page

This is an Angular 17 single-page application utilizing the latest version of keycloak-angular (15.2.1 at the time of writing). I'm facing a perplexing issue where after successfully authenticating and logging out, if I reload the page, it breaks enti ...

Exploring Transformation in Angular

I am looking to enhance my understanding of how ChangeDetection works, and I have a query in this regard. When using changeDetection: ChangeDetectionStrategy.OnPush, do I also need to check if currentValue exists in the ngOnChanges lifecycle hook, or is i ...

Tips for refining a list to only include items that contain every element from a specified array

Is there a way to search for all elements in an array and display them if they are all present? For instance, consider the following: const data = [ { "languages": ["JavaScript"], "tools": ["React", "Sass"] }, { "languages": ["Python" ...

Developing desktop applications using C# scripting

I currently have a C# desktop program that is able to work with new C# plugins. My goal is to modify the existing C# application to allow for scripts to be used as plugins. These scripts could be in JavaScript, Windows Script Host (WSh), or any other form ...

The functionality of a div element appears to be impaired when attempting to include a newline character

I have a div element <div id="testResult" style="padding-left: 120px;"> My goal is to include text with newline character '\n' inside the div. However, when I view my html page, the text does not respect the newline character. $( ...

Using Ajax and jQuery to redirect a page with values in ASP.NET

I have two pages: Default.aspx and DetailView.aspx. My goal is to redirect from Default.aspx to DetailView.aspx using an AJAX call and pass a value as well. Although I have tried something, the function defined in the class is not being called. The functi ...

Tips on updating primeng Panel Menu appearance with scss

I'm looking to customize the color of my panel menu to black. Below is the HTML code I am using. <p-panelMenu styleClass="font-bold text-xs m-0 w-11" [model]="items" [multiple]='false'></p-panelMenu> ...

Attempting to streamline the process of verifying the truthfulness of an object key and subsequently adding it to a different

In the process of creating a form to interact with a remote API, I aim to construct a GET request query string depending on which checkboxes the user chooses. Initially, I considered using a series of if/else statements to check whether the model object k ...

Different ways to verify if a Checkbox is selected within a table

As a newcomer to reactjs, I have a component that renders two tables with different data using the same component and passing data through props. Each table has checkboxes for selection. If a user selects items from both tables, I want to detect if they ha ...

Using Javascript in n8n to merge two JSON arrays into a single data structure

When working on a project, I extract JSON objects from the Zammad-API. One of the tickets retrieved is as follows: [ { "id": 53, "group_id": 2, "priority_id": 2, "state_id": 2, "organizati ...

Updating the parent page host within a cross-domain iframe: issues encountered in Firefox and Chrome browsers

I am encountering an issue with my iframe app where I am receiving an alert indicating "-error" in Chrome related to top.location.href. jQuery.ajax({ type : 'get', url : 'check_if_fb_data_set.php', success ...

Persistent error caused by unresponsive Tailwind utility functions

Currently, I am working on a Next.js application and encountered a strange error while adjusting the styling. The error message points to a module that seems to be missing... User Import trace for requested module: ./src/app/globals.css GET /portraits 500 ...

Having trouble displaying API values in b-form-select component in Vue.js?

I am using an API to fetch users data and I want to bind these users to a b-form-select component in Bootstrap Vue. However, after making the request, I only see "null" in the b-form-select. Here is my request: getAllUsers() { axios.get(&a ...