目前,我正在尝试决定在处理 Promise 中的错误时应该使用哪种模式。例如,我有下面的代码
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 block 并拒绝来自 catch 的 Promise。
最佳答案
What approach should be used to reject the Promise if a function inside it (setTimeout(), in my case) throws an Error
异步回调绝不能抛出异常。您尝试 promise 的函数 ( setTimeout
) 要么抛出同步异常(由 new Promise
处理),要么调用回调。在回调中,您必须调用 resolve
或 reject
,并在不抛出异常的情况下执行此操作。
如果您想在回调中做额外的事情(除了调用 resolve
/reject
),可能会引发异常的事情:不要!
new Promise
应该只包装你想要 promise 的直接功能,没有别的。在then
做更多的事情链接到 promise 的回调 - then
将在其回调中处理异常:
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";
});
}
关于javascript - 在 Promise 中处理错误的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53803876/