Search code examples
javascriptnode.jspromisees6-promise

Escape multiple nested functions in NodeJS


I have code in Javascript that looks like this:

function someFunction() {
    // Code
    somePromise().catch(err => {
        console.log(err);
    });
    // Mode Code
}

I would like to escape both somePromise().catch and someFunction() in the event that somePromise() is rejected. I tried using return but that only allows me to escape somePromise().catch. Is there any function that would allow me to break out of nested loops?


Solution

  • You can do that by using async/await:

    function async someFunction() {
        // Code
        try {
            await somePromise();
        } catch (err) {
            console.log(err);
            return; // aborts further execution
        }
        // More Code
    }
    

    See async function for details.