【发布时间】:2018-04-27 21:14:58
【问题描述】:
我正在掌握 Promise 以及如何设置它们,但是我不明白为什么 node 认为我的 Promise 在涉及错误时未处理...有人可以解释一下吗?
我的简单代码
// Setting up the Promise
function add(x, y) {
return new Promise((response, reject) => {
// Simple conditional (not perfect, but it just proves a point)
if(x !== null && y !== null) {
// I know I could have done 'response(x + y)', but I wanted
// to console.log the result also
var calc = x + y
response(calc)
console.log('Calculation: ' + x + ' + ' + y + ' = ' + calc)
} else {
// My console does not throw this error?
reject('One of the inputs was null')
}
})
}
// Function using the Promise
function calc() {
add(1, 3)
.then(res => add(res, 3))
.then(res => add(res, null))
.then(res => console.log('Final result: '+res))
.catch(err => {
// This error is thrown in console
throw new Error('Something went horribly wrong')
})
}
// Run the code
calc();
更新
我最初发布了带有抛出错误的“拒绝”,我知道需要捕获该错误。
我还想了解为什么在我的控制台中看不到“拒绝”中的字符串?
控制台输出:
Calculation: 1 + 3 = 4
Calculation: 4 + 3 = 7
(node:61950) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Something went horribly wrong
(node:61950) [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.
【问题讨论】:
-
如果你在
catch子句中抛出一个新错误,它将沿着承诺链传播。所以你需要第二个catch来捕捉你在第一个catch 中抛出的错误。你可能只想在抛出它的时候返回reject子句中的字符串,因为你在reject中返回的内容将被用作catch中的错误。 -
谢谢@Shilly - 我已经编辑了我的问题。我理解您对需要捕获的抛出错误的意思,但是如果我不抛出任何东西,而只有
reject('some error message'),那又如何呢?我在控制台中没有看到错误消息? -
@Shilly - 啊,我知道
reject()部分就像response()部分一样,它需要在那个时候传递或调用一些东西。输入reject(console.log('Rejection message'))失败时会打印到控制台,但是我仍然收到UnhandledPromiseRejectionWarning: Unhandled promise rejection -
您仍然在未处理的捕获中抛出错误。编辑后,
catch内的err等于“其中一个输入为空”,因为这就是您拒绝承诺的原因。因此,如果您需要将这两件事都记录到控制台,只需将catch处理程序更改为console.error( err ); console.error( 'Something went horribly wrong' )以便记录被拒绝的文本和 catch 内的文本。由于这是您最后一个 catch 处理程序,因此您希望在那里结束错误链。
标签: javascript node.js promise es6-promise