Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I don't understand... Is it me or is this a bug in node?

This is fine as expected:

const a = new Promise((resolve, reject) => {
  setTimeout(() => reject('timeout'), 1000);
});
a.catch(console.log);

And this is throwing a warning:

const a = new Promise((resolve, reject) => {
  setTimeout(() => reject('timeout'), 1000);
});
a.then(console.log);
a.catch(console.log);

I get

timeout
(node:40463) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): timeout
(node:40463) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
493 views
Welcome To Ask or Share your Answers For Others

1 Answer

Annotated and slightly modified source:

// promise A is created
const a = new Promise((resolve, reject) => {
  setTimeout(() => reject('timeout'), 1000);
});

// promise A is chained with .then()
// means new promise is created
// and only resolve catched here
const aThenPromise = a.then(console.log);

// promise A is chained with .catch()
// means new promise is created
// and only reject catched here
const aCatchPromise = a.catch(console.log);

// aThenPromise !== aCatchPromise

When promise a is rejected:

  • aCatchPromise works as expected, and timeout is logged to console
  • aThenPromise does nothing, as it works only with resolve(), and reject is passed through it, and not handled because it is different Promise. This leads to UnhandledRejection

You need to add catch to aThenPromise,

One possible option is a.then(console.log).catch(console.log) this will handle rejection passed through .then


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...