处理Promise中错误的正确方法 [英] correct way to handle errors inside a Promise
问题描述
当前,我正在尝试确定在Promise中处理错误时应使用的模式.例如,我有下面的代码
Currently, I'm trying to decide what pattern I should use while dealing with errors inside a Promise. For instance, I have the code below
promiseFunc()
.then(result => {
console.info(`.THEN:: ${result}`)
})
.catch(error => {
console.info(`.CATCH:: ${error}`)
})
function promiseFunc() {
return new Promise((resolve, reject) => {
setTimeout(() => {
throw Error("setTimeout's callback error")
resolve('resolution')
}, 1000)
})
}
我无法获得的是,如果其中的一个函数(在我的例子中是setTimeout())抛出错误,则应该使用哪种方法来拒绝Promise.换句话说,我需要一个拒绝而不是一个错误,但是我想到的唯一想法是添加一个try/catch块并从捕获中拒绝Promise.
What I can't get is what approach should be used to reject the Promise if a function inside it (setTimeout(), in my case) throws an Error. In other words, I need a rejection instead of an error, but the only idea that comes to my mind is to add a try/catch block and reject the Promise from the catch.
推荐答案
如果其中的一个函数(在我的例子中是setTimeout())抛出错误,应该使用哪种方法拒绝Promise
What approach should be used to reject the Promise if a function inside it (setTimeout(), in my case) throws an Error
异步回调绝对不能抛出异常.您尝试实现的函数( setTimeout
)要么抛出同步异常( new Promise
处理),要么调用回调.在回调中,您必须调用 resolve
或 reject
,并且必须执行此操作,而不会引发异常.
An asynchronous callback must never throw an exception. Your function that you try to promisify (setTimeout
) either throws a synchronous exception (which new Promise
handles), or it calls the callback. In the callback you must call resolve
or reject
, and do so without throwing an exception.
如果您想在回调中做其他事情(除了调用 resolve
/ reject
),可能会引发异常的事情:不要!
If you want to do additional things in the callback (besides calling resolve
/reject
), things that could throw an exception: don't!
新的Promise
应该只包装您要承诺的立即函数,而不能包装其他任何东西.在链接到Promise的 then
回调中做更多的事情- then
将在其回调中处理异常:
The new Promise
should wrap only the immediate function that you want to promisify, nothing else. Do more things in then
callbacks that are chained to the promise - then
will handle exceptions in its callback just fine:
function promiseFunc() {
return new Promise(resolve => {
setTimeout(resolve, 1000);
// ^^^^^^^ nothing can go wrong in here
}).then(() => {
throw "setTimeout's callback error";
// ^^^^^ here, it will lead to a rejection
return "resolution";
});
}
这篇关于处理Promise中错误的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!