【问题标题】:Function in then() promise resolver always fires even if primise fails即使 primise 失败,then() 承诺解析器中的函数也总是会触发
【发布时间】:2020-07-07 18:31:41
【问题描述】:

当我单击一个按钮时,我触发了一个 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 });
        });
    }

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 2018-05-25
      • 2017-08-19
      • 2020-10-29
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      相关资源
      最近更新 更多