Search code examples
javascripterror-handlingpromisedom-eventsglobal

Continuing code after an unhandledrejection event


https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event

The unhandledrejection event is sent to the global scope of a script when a JavaScript Promise that has no rejection handler is rejected; typically, this is the window, but may also be a Worker.

What does the phrase "event is sent to the global scope of a script" mean?

Does it mean that after an unhandled rejected promise the script cannot continue?

I don't understand what that refers to

addEventListener('unhandledrejection', (event) => {
  console.log('unhandledrejection');
  console.log(event.promise);
  console.log(event.reason);
});
Promise.reject('sss');

Solution

  • "Scope" is probably a misleading term here. A DOM event is always dispatched on an object, not on a variable scope. However, the unhandledrejection event is a global event that pertains to the realm (script environment) as a whole, not to invidivual objects (e.g. the promise that was rejected or the DOM node whose event handler errored). So it is fired on the global object, which is window in normal script environments and self in a web worker. These global objects are also used as the root of the global variable scope though, which is why you can access their properties and methods without dot notation. So you can just call addEventListener(…); and it's the same as calling self.addEventListener(…); or window.addEventListener(…);.

    Does it mean that after an unhandled rejected promise the script cannot continue?

    No. unhandledrejection and error events in a browser context are just that: events. They may be handled or not, but the page stays interactive. Code in a worker can continue to receive and process more events.

    It's only in node.js where an unhandled rejection (or exception) by default terminates the process.