Sending an error from one asynchronous function to another

I have a complex system that utilizes async/await. My goal is to handle various types of errors from an async function within a single try/catch block. This function is called from another async function.
Unfortunately, I've been unable to successfully handle exceptions in the parent async function. When attempting to do so as shown below, I only receive a warning about an unhandled promise rejection and the catch block in the parent function never captures the error. I've even tried throwing an error without success.

const die = (message) => new Promise((resolve, reject) => reject(message));

const survive = () => new Promise((resolve, reject) => resolve(true));

const childAsync = async () => {
    await survive();
    try {
        await die('farewell');
    } catch (error) {
        return Promise.reject(error);
    }
    try {
        await die('enjoy your time');
    } catch (error) {
        return Promise.reject(error);
    }
    await survive();
};

const parentAsync = async () => {
    try {
        childAsync();
    } catch(error) {
        console.log('caught an error'); // never executed
        console.log(error);
    }
};

parentAsync();

I seem to be missing something crucial about async functions in order to achieve this task

Answer №1

The line daughterAsync(); in your code only initiates the promise, but it does not store the reference to it or wait for it to resolve. To properly handle errors in the daughterAsync function, you must use the await keyword inside the try block of the parentAsync function:

const die = (word) => new Promise((resolve, reject) => reject(word));

const live = () => new Promise((resolve, reject) => resolve(true));

const daughterAsync = async () => {
    await live();
    try {
        await die('bye');
    } catch (err) {
        return Promise.reject(err);
    }
    try {
        await die('have a beautiful time');
    } catch (err) {
        return Promise.reject(err);
    }
    await live();
};

const parentAsync = async () => {
    try {
        await daughterAsync();
    } catch(err) {
        console.log('error caught');
        console.log(err);
    }
};

parentAsync();

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

Updating a Texture Image in Three.js

I'm currently working on a minecraft texture editor using three.js, with a similar interface to this. My goal is to implement basic click-and-paint functionality, but I'm facing challenges in achieving this. I have textures for each face of every ...

Learning to implement $first in an Angular ng-repeat to dynamically add a new table row

I am currently facing an issue with displaying a Google map for addresses in my Angular application. The problem seems to be related to the asynchronous nature of HTML and JS, but I am struggling to find a solution. The issue is that even though the map vi ...

Attempting to alter the background image through the action of clicking on an image using jQuery, HTML, and CSS

I have created custom weather icons like a sun, cloud, and rainy cloud using Photoshop. My goal is to allow users to click on these icons and change the background image of the website's body. However, despite my efforts, clicking on the images does n ...

Please ensure to refresh the page after confirming the alert box by clicking OK

Is it possible to clear certain inputs on my Magento store's checkout page when an alert box is displayed and the user clicks OK? Unfortunately, I do not have control over the JavaScript alert. Therefore, I thought of implementing a script that can d ...

Struggling with properly navigating a JSON file in my JavaScript code... specifically trying to access and retrieve the "responseObject.weather[i].weatherresponseObject.weather[i].description" data

Struggling with extracting data from a PHP file in JSON format to display on an HTML file using JavaScript. I seem to be encountering issues with accessing responseObject.weather[i].weatherresponseObject.weather[i].description, and I suspect it might be d ...

If the cursor hovers over an image, the onmouseover function does not work properly

Currently, I am developing a PHP page to display data from a database in a tabular format. Each column in the table represents an 'ATC Station'. When active, additional data is displayed upon hovering over the cell. Everything was running smooth ...

Invoke a PHP function located in a separate file using a JavaScript function to fetch data from a database

How can I properly call a PHP function from a JavaScript function located in a different file? I am trying to pass a variable from an onClick function in JavaScript to a PHP function, which will then access a MySQL database to retrieve data. However, my c ...

My Angular7 app.component.html file is not displaying the routing. What could be the issue?

After implementing the code in app.component.html in Angular 7 like this: <div id="wrapper"> <header id="header-container" class="fullwidth"> <div id="header"> <div class="container"> <div class="left- ...

Directing users to a specific section on another webpage can be accomplished using HTML, JavaScript, or

<nav> <div class='container-fluid'> <h1 class='logo'>Logo</h1> <ul class='list-unstyled naving'> <li><a href='index.html'>Home</a></li> ...

Tips for preventing the use of eval when invoking various functions

Here's a snippet of code I've been using that involves the use of eval. I opted for this approach as it seemed like the most straightforward way to trigger various factory functions, each responsible for different web service calls. I'm awa ...

Elevate your website's design with Vue and create eye-catching CSS

I've been working on a Vue hamburger menu component, but I'm facing an issue with the animations. The animation process seems to reach the desired end result, yet there is no actual animation displayed. The animation triggering is done through a ...

hashSync function needs both data and salt to generate the hash

I can't figure out why I am encountering this issue, I have checked the documentation and couldn't find my mistake. Any suggestions? Error: data and salt arguments required const {create} = require('./user.service'); const {genSaltS ...

Create a notification box that appears after a successful axios request

One of the functions I have is to store an expense in my application. storeExpense(context, params){ axios.post('api/expenses', params) .then( response => { context.dispatch('getExpenses') }) .catch( error =&g ...

I am unable to implement code coverage for Cypress in Debian at the moment

Having trouble obtaining code coverage results using Cypress in my Virtual Machine (Debian Bullseye), but no issues when I run the same project on my Windows machine. On Linux, the code coverage shows up as: Click here to view Index.html inside lcov-repor ...

In search of a JavaScript library that can help format strings to meet the requirements of JSON formatting

Utilizing jQuery ajax, I am transmitting updates from the client's browser to my server. However, I have noticed that there are certain characters not supported by JSON that require an additional "\" in front of each one to be properly sent. The ...

React-file-viewer shrinks any document to a compact size

I have been searching extensively for information on how to adjust file sizing in react-file-viewer without any success. My objective is to utilize the react-file-viewer to allow users to click on a filename hyperlink and open the file (be it an image, do ...

Having trouble downloading the Chip component in Material-UI? Learn how to fix the download issue

I used the UI to upload a file, and now I want to download it either after some time or instantly. I tried implementing this using the <Chip> component, but it's not working. I need assistance in resolving this issue. Uploaded File: const data ...

Refreshing the Table to Update Data

I am working on a jquery application that includes a table with time and number fields. My goal is to increment the values every 3 seconds by creating a function to update the numbers automatically. Initially, the data in the table looks like this: Kobe ...

JQuery Mobile fails to apply consistent styling to user input check items within a list

I have successfully implemented the functionality to add user input items to a checklist. However, I am facing an issue where the newly added items are not adhering to Jquery Mobile's styling. Here is a screenshot showcasing the problem: Below is th ...

Incorporating Javascript .click() with Python Selenium Webdriver for Enhanced Script Functionality

Having trouble incorporating Javascript code into my Python Selenium script. The ".click()" method in Javascript is more efficient than Selenium. I need to translate this Javascript into Python, but I'm not familiar with JS : const MyVariable= $(&quo ...