简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM