gpt4 book ai didi

javascript - 在 Promise 中处理错误的正确方法

转载 作者:搜寻专家 更新时间:2023-10-31 23:44:30 25 4
gpt4 key购买 nike

目前,我正在尝试决定在处理 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 处理),要么调用回调。在回调中,您必须调用 resolvereject ,并在不抛出异常的情况下执行此操作。

如果您想在回调中做额外的事情(除了调用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com