gpt4 book ai didi

promise ,如果发生错误,不要触发 'then'

转载 作者:行者123 更新时间:2023-12-05 04:11:54 25 4
gpt4 key购买 nike

我正在尝试构建一个简单的 CRUD 应用程序。用户有一个个人资料页面,可以填写关于他自己的字段并保存。我的问题是:

我正在为 http 请求使用 axios(在 Redux 应用程序中):

export const createCard = (data) => (dispatch) =>
axios.post('/api/cards', data)
.then(
response => dispatch({
type: actions.CREATE_CARD_SUCCESS,
card: response.data
})
error => dispatch({
type: actions.CREATE_CARD_FAILURE,
message: error.message
})
)
.then(() => /* do something here, if no error occur */);

在请求成功完成后,我想在 then 方法中做一些事情。但它总是触发,即使发生错误也是如此

可以这样实现:

export const createCard = (data) => (dispatch) =>
axios.post('/api/cards', data)
.then(
response => {
dispatch({
type: actions.CREATE_CARD_SUCCESS,
card: response.data
});
},
error => {
dispatch({
type: actions.CREATE_CARD_FAILURE,
message: error.message
});
return error;
}
)
.then(error => {
if (!error) {
/* do something here, if no error occur */
}
});

但是样板太多了。

在这种情况下,Jquery.ajax 很方便。

$.ajax()
.done()
.fail()
.always()
.then(() => { /** this callback will be fired if no error occur **/})

我如何在 axios 或获取 api 中模拟这种行为?

最佳答案

看起来您有一个 promise 拒绝处理程序来处理拒绝,并且不小心将 promise 从 rejected 转回 resolved,因此即使发生错误,您的后续 .then() 处理程序也会被调用。

当您使用 .catch() 或第二个回调到 .then() 创建 promise 错误处理程序时,如下所示:

p.then(result => {
// do something with result here
}, err => {
console.err(err);
}).then(result => {
// this will always get fired because you "ate" the error in the previous catch handler
});

并且,您在不重新抛出或不返回被拒绝的 promise 的情况下处理错误,然后 promise 基础结构认为您已经“处理”了错误并且父 promise 被解决(不再被拒绝)。因此,任何后续的 .then() 处理程序都将被调用,即使在链中较早的时候发生了错误。

如果您想对错误做一些事情(比如记录它或执行一些其他逻辑),但您希望 promise 保持被拒绝状态,那么您必须重新抛出错误或返回一个被拒绝的 promise。这是保持链条被拒绝的唯一方法。


虽然您问题中的代码似乎缺少逗号,但看起来这应该是 .then() 处理程序的第二个参数,因此会在 promise 时被调用拒绝:

       error => {
dispatch({
type: actions.CREATE_CARD_FAILURE,
message: error.message
});
return error;
}

因为你只是在做一个普通的返回错误,这将改变要解决的 promise (不再被拒绝),因此下面的 .then() 处理程序得到打电话。

要保持 promise 被拒绝,您可以重新抛出错误(使用 ES6 标准的兼容 promise )或者您可以返回被拒绝的 promise (使用 jQuery .then() 处理程序或 ES6 标准的兼容 promise ) :

       error => {
dispatch({
type: actions.CREATE_CARD_FAILURE,
message: error.message
});
// keep the promise rejected
return Promise.reject(error);
}

注意:这与 try/catch 对常规同步代码的工作方式非常相似。当您执行 catch() 时,异常会被处理并且不会向上传播,除非您重新抛出它。 promise 捕获处理程序也是如此。

关于 promise ,如果发生错误,不要触发 'then',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41823285/

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