首页 > 解决方案 > 即使 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 });
        });
    }

标签: javascriptvue.js

解决方案


当你处理你的错误时,你会阻止错误被传播到 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;
  }
);

推荐阅读