Search code examples
javascriptnode.jsasync-awaitpromise

Turn not awaited unhandled erroneous promise into warning @ processTicksAndRejections (created by throw error in "then")


there is no await on top-level allowed and my expectation was that the error thrown below would be logged as warning only but it turns out to be a blocker for completion, i.e. upon statement await fsProm.stat the processing basically stops. I would not understand why?

const fsProm = require('fs').promises;

async function codeWithUnhandledPromise(){
    const notAwaited = Promise.resolve().then(function(){
        throw new Error('Irrelevant');
    });
    await fsProm.stat( __filename );
    console.log( 'Not reached' );
}
async function main(){
    try {
      await codeWithUnhandledPromise();
    } catch (error) {
      console.log( 'Not reached' );
    } finally {
      console.log( 'Not Reached' );
    }
}

main().then(undefined,function(){ 
    console.log( 'Not Reached' );
    return;
});
console.log( 'done' );

Solution

  • The reason you're seeing neither fulfillment nor rejection of the promise from codeWithUnhandledPromise is that Node.js now terminates the process on unhandled rejections. You can modify that behavior with the --unhandled-rejections command-line flag.

    For years, versions of Node.js warned that unhandled rejections would, in some future version, terminate the program. For instance, if you ran that code with Node.js v14, you'd get this warning:

    [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

    It's no longer a warning (unless you enable it again). The standard behavior now aligns with unhandled exceptions: they terminate the program.