捕获被拒绝的承诺后,处理提出拒绝警告

使用Node v8.1.4运行以下代码:

testPromise((err) => { if (err) throw err; }); function testPromise(callback) { Promise.reject(new Error('error!')) .catch((err) => { console.log('caught'); callback(err); }); } 

返回以下内容:

 caught (node:72361) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: test (node:72361) [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. 

我会期待一个uncaughtException被抛出? 我怎样才能把它变成一个未捕获的exception?

你本质上是抛出catchcallback。 这被抓住,变成另一个被拒绝的承诺。 所以你不会得到uncaughtException

 Promise.reject("err") .catch(err => { throw("whoops") //<-- this is caught }) .catch(err => console.log(err)) // and delivered here -- prints "whoops" 

要注意的一件事是抛出的asynchronous函数。 例如,这是一个未捕获的exception:

 Promise.reject("err") .catch(err => { setTimeout(() => { throw("whoops") // <-- really throws this tim }, 500) }) .catch(err => console.log(err)) //<-- never gets caught.