Search code examples
javascriptes6-promise

Handling unhandled promise rejections: Difference between onunhandledrejection and unhandledrejection


In MDN there are two events that are fired when a promise rejection is unhandled.

They both have the same compatibility so I wonder what is the difference between onunhandledrejection and unhandledrejection?


Solution

  • That's the case for almost every window EventListener in JavaScript. See for example the keypress-event below:

    window.addEventListener("keypress", () => console.log("Key pressed!"));
    window.onkeypress = () => console.log("Key pressed!");
    

    The main difference between both methods of attaching an EventListener to the window element is:

    • using the 'addEventListener()'-method, you'll be able to subscribe multiple event listener functions to a single event.
    • using the 'window.onunhandledrejection'-property you are only able to assign one function to the property, which will be triggered on the same event. So if you would later assign another function to the property, it will overwrite your initial assignment.

    Example:

    window.addEventListener("keypress", () => console.log("Key pressed! Listener 1"));
    window.addEventListener("keypress", () => console.log("Key pressed! Listener 2"));
    window.onkeypress = () => console.log("Key pressed! Listener 3");
    window.onkeypress = () => console.log("Key pressed! Listener 4");
    
    // If the user presses any key, the Events will be triggered in the order of assignment.
    // The console output would be:
    
    // Key pressed! Listener 1
    // Key pressed! Listener 2
    // Key pressed! Listener 4
    

    Also have a look at this very detailed answer, which explains the pros and cons of both methods!