Neal Neal - 2 months ago 4x
Javascript Question

According to the documentation throwing an error in a promise will reject it, but it does not

According to Introduction:

// Throwing an Error will also reject the promise
// throw new Error(reason);

I tried that here:

const promise = new Promise(function(resolve, reject) {
var result = 1;

// This could also be a web request, or anything else either synchronous or asynchronous
setTimeout(function() {
result += 10;


document.body.addEventListener("click", function clickHandler() {
document.body.removeEventListener("click", clickHandler);

throw new Error("You clicked");

document.body.innerText = "Working... Click anywhere to reject the promise with an error.";

promise.then(function(value) {
document.body.innerText = "Everything went fine! The Promise resolved with: " + value;
}).catch(function(error) {
document.body.innerText = "Something went wrong: " + error;

body {
margin: 0;
padding: 8px;
min-height: 100vh;
box-sizing: border-box;

But it ends up with an error and resolves fine.

Is the documentation wrong? Or am I doing something wrong?


You are not throwing the error within the context of the promise, you error is happening within the context of the click handler, after you create the promise.

const promise = new Promise(function(resolve, reject) {

    document.body.addEventListener("click", function clickHandler() {
        // this is not part of the promise and executes sometime later

This means the code within the promise, including the attachment of the listener, will happen when the promise is created and no errors happen at that time.

Sometime later, whenever your click event fires, you will throw an error asynchronously, within a completely separate context.

const promise = new Promise(function(resolve, reject) {
    // Any error that happens here will result in a promise rejection

    document.body.addEventListener("click", function clickHandler() {
        // Any error that happens here will be thrown within the handler,
        // after the promise was created and resolved

As mentioned by Kevin B in the comments, the documentation explains this as well.