首页 > 解决方案 > 当 ajax 调用在 axios 中成功时做一些事情 - 在 axios 中链接 then()

问题描述

当 ajax 调用在 axios 中成功时,我正在尝试做某事

    save() {

      this.isUpdateTask ? this.updateProduct() : this.storeProduct()

      this.endTask()

    }

如果更新或存储产品的 ajax 调用成功,我想运行 endTask() 函数。

我不希望在 ajax 调用不成功时运行 endTask() 函数。

我怎样才能做到这一点?

商店功能:

    storeProduct() {
      return axios
        .post("products", this.getFormData())
        .then(
          response => this.products.push(response.data.data)
        )
        .catch(
          error => (this.serverErrors = error.response.data.errors.detail)
        )
    },

标签: javascriptajaxvue.jsaxios

解决方案


您可以在新的 Promise 中调用此方法,如下例所示:


   save() {
      Promise.resolve()
      .then(() => {
        return this.isUpdateTask ? this.updateProduct() : this.storeProduct()
      })
      .then(() => {
        this.endTask()
      })
    }

还有其他方法可以做:

save() {
  (this.isUpdateTask ? this.updateProduct() : this.storeProduct()).then(() => {
    this.endTask()
  })
}

或分配给一个变量:

save() {
  const promiseUpdate = this.isUpdateTask ? this.updateProduct() : this.storeProduct()

  promiseUpdate.then(() => {
    this.endTask()
  })
}

或者使用异步/等待:

async save() {
  await this.isUpdateTask ? this.updateProduct() : this.storeProduct()
  // this code runs only if everything happen successful
  await this.endTask()
}

关于endTask执行直到响应不成功,是因为您对待errorstorProduct 内部。

.catch(
  error => (this.serverErrors = error.response.data.errors.detail)
)

因此,在这种情况下,有必要再次重新抛出错误:

.catch(
  error => {
    this.serverErrors = error.response.data.errors.detail
    throw error
  }
)

Promise的catch作用与try/catchfrom javascript 相同。

在这里有更多关于catch承诺的参考。


推荐阅读