tilin
tilin

Reputation: 332

Strange Unhandled promise rejection

Can't understand why the behavior is different. In this version everything works as expected:

const debug = require("debug")("m");

const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        reject("promise rejected");
    }, 1000);
});

promise.then(
    v => {
        debug("resolve", v);
    },
    e => {
        debug("reject", e);
    },
);

Put a catch handler instead of reject handler:

const debug = require("debug")("m");

const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        reject("promise rejected");
    }, 1000);
});

promise.then(v => {
    debug("resolve", v);
});

promise.catch(e => {
    debug("catch: ", e);
})

works the same, but nodejs warning UnhandledPromiseRejectionWarning. How to understand this?

Upvotes: 0

Views: 463

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075755

One of the key things about then and catch is they create new promises. (See the Promises/A+ spec* and the JavaScript spec ["NewPromiseCapability" is the spec's way of saying "create a new promise"].) The promise the then handler in your second example is creating is rejected because its underlying promise is rejected, and that rejection is never handled.

The usual way to do it with catch would be a chain:

promise
    .then(v => {
        debug("resolve", v);
    })
    .catch(e => {
        debug("catch: ", e);
    });

That way, there is no unhandled rejection (and errors thrown in the then callback, if any, are propagated as a rejection to the catch).


* Promises/A+ allows then to return the same promise provided the implementation meets all the other requirements, but JavaScript's Promises don't.

Upvotes: 2

Related Questions