Search code examples
javascriptnode.jsecmascript-6es6-promiseecmascript-5

How to handle an unexpected error from a function after result is return from function in JavaScript?


While working on asynchronous functions in JavaScript. I discovered this problem.

A function needs to perform some asynchronous task, however that task doesn't make difference to function result. So function return its result, and after a while an exception is thrown from asynchronous function, however since control is already returned so exception goes unhanded.

Note: Not to change notify I'm intentionally throwing error like that, need to only handle this exception

Code is like:

function notify() {   //To send notification
    setTimeout( function() {   //Just to simulate an asynchronous function
        throw "Exception occurred";   //An exception from async function
    },2000);

    return "Notified";
}

try {
    let result = notify();
    console.log(result);    //Notified
}
catch (error) {   //Never comes to catch block.
    console.log(error);
}

How can to catch this exception. Tried using Promise, however it doesn't resolved with promise because even with promise, flow or function is removed from memory as calling function have received response.

Code using Promises

function notify() {   //To send notification

    return new Promise ( (resolve, reject) => {
        setTimeout( function() {   //Just to simulate an asynchronous function
            throw "Exception occurred";   //An exception from async function
        },2000);

        resolve("Notified");
    });
}

notify()
.then( result => {
    console.log(result);    //Notified
})
.catch( error => {   //Never comes to catch block
    console.log(error);
});

How can I catch exception in JavaScript programming?


Solution

  •     var notify = function () {
            anOddTask();
            return "Notified";
        }
    
    
        async function anOddTask() {
            try {
                await setTimeout( function() {  
                },2000);
                throw new Error("Exception occurred");
            }
            catch (err) {   
                console.log(err);
            }
        }
    
        try {
            let result = notify();
            console.log(result);    //Notified
        }
        catch (error) {   //Never comes to catch block.
            console.log(error);
        }
    

    This will immediately return "Notify" and handle the rejection at some later time. If you wish that "Notify" be returned as a resolved promise than just make notify() an async function.

        var notify = async function () {
            anOddTask();
            return "Notified";
        }