javascript - 即使 primise 失败,then() 承诺解析器中的函数也总是会触发
问题描述
当我单击一个按钮时,我触发了一个 vuex 操作,此操作从 vuex 商店返回一个 axios 承诺,在我的组件中,我只想在操作成功时重置表单文件,但是现在它总是重置表单文件,即使承诺失败......我正在使用 then 并 catch 来实现这个目的,在 then 解析中触发了 resetForm 方法,遗憾的是无论如何它总是会重置......
这是我的组件中的代码:
const self = this;
this.sendContactMail(payload)
.then((response) => {
//This always fires, even if promise fails
self.resetData();
},
(error) => {
});
我的 vuex 操作:
sendContactMail({ commit }, payload)
{
commit('Loader/SET_LOADER', { status:1 }, { root: true });
return axios.post('/api/contacts/send-contact-mail', payload)
.then((response) => {
commit('Loader/SET_LOADER', { status:2, response: response }, { root: true });
},
(error) => {
commit('Loader/SET_LOADER', { status:3, errors: error }, { root: true });
});
}
解决方案
当你处理你的错误时,你会阻止错误被传播到 Promise 链上。如果您希望错误在处理后继续上升,则必须在错误处理逻辑中重新抛出它,例如
return axios.post("/api/contacts/send-contact-mail", payload).then(
response => {
commit("Loader/SET_LOADER", { status: 2, response: response }, { root: true );
},
error => {
commit("Loader/SET_LOADER", { status: 3, errors: error }, { root: true });
throw error;
}
);
推荐阅读
- php - PHPMailer 不工作:有新的方法吗?
- python - Pandas 数据框分组求和,同时忽略非数值
- tensorflow - 修复 seq2seq 模型的错误输出
- arrays - 如何使用 eloquent 在数组数组中搜索字符串
- angular - (Angular 2+)尝试设置基于 sessionStorage 的 var ngOnInit() 但在页面加载后未定义
- docker - 如何在 docker 容器中导出 DGraph 数据库(Windows)
- java - 错误:找不到属性“com.example.b3rk4.myapplication:layout_constraintTop_toTopOf”
- php - JSON API 到 HTML Koinex API
- javascript - 如何在多个鼠标悬停上更改光标
- d3.js - Music21 和 D3.js 用于音乐特征提取和可视化?