Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

javascript - Unhandled promise rejection despite catching the promise

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...