Search code examples
javascriptnode.jspromisees6-promise

Weird behavior with Promise throwing "Unhandled promise rejection" error


When I run this code using Node, it throws an Unhandled promise rejection error in the console (even showing the error caught text first).

const promise = new Promise((resolve, reject) => setTimeout(reject, 1000))
promise.then(() => console.log('ok'))
promise.catch((e) => console.log('error caught'))

Nevertheless, when I chain the catch method to the then method, the error disappears:

const promise = new Promise((resolve, reject) => setTimeout(reject, 1000))
promise.then(() => console.log('ok')).catch((e) => console.log('error caught'))

Isn't the first code supposed to handle the rejection?

I also tried the first code in Chrome and it works if I open the inspector when I'm in a new tab (or google.com). If I'm in any other page (like stackoverflow.com) it throws the exception. Any explanation to this? This seems really weird to me!


Solution

  • In order to be considered handled, rejected promises should be synchronously chained with then(..., ...) (2 arguments) or catch(...).

    promise.then(() => console.log('ok')) is a separate promise that wasn't chained with catch(...), so rejected promise will result in unhandled rejection.

    If I'm in any other page (like stackoverflow.com) it throws the exception

    This isn't an exception, it doesn't prevent a script from running normally. The way unhandled rejections are treated depends on Promise implementation. Chrome implementation results in Uncaught (in promise) console error by default.

    That it doesn't appear on some websites in Chrome means that a website set up unhandledrejection event handler that suppresses error output.