1
votes

I have a convoluted system, which totally works on async/await. What I want is to handle multiple types of errors from an async function in one and only try/catch block. Which means that I call this function from another async function.
But the concept of handling exceptions in a parent async function seems to fail. In the below example what I get - is just a warning about unhandled promise rejection, and the catch block in the parent won't ever get an error. I've tried this also with simply throwing and error, but unsuccessfully either.

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 beatiful time');
    } catch (err) {
        return Promise.reject(err);
    }
    await live();
};

const parentAsync = async () => {
    try {
        daughterAsync();
    } catch(err) {
        console.log('error catched'); // never happens
        console.log(err);
    }
};

parentAsync();

I have a feeling that I don't get something about async functions to perform such a stunt

1
As a note: in an async function you do not need to write return Promise.reject(err); you could just write throw err.t.niese

1 Answers

2
votes

Your daughterAsync(); line only starts the promise running, but it doesn't save the reference to it or wait for it to resolve. You need to await the promise returned by daughterAsync inside of parentAsync's try block in order to catch errors in daughterAsync:

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 beatiful time');
    } catch (err) {
        return Promise.reject(err);
    }
    await live();
};

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

parentAsync();