在axios中成功执行ajax调用时执行某些操作-在axios中链接then()

时间:2019-09-24 11:47:00

标签: javascript ajax vue.js axios

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

    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)
        )
    },

3 个答案:

答案 0 :(得分:2)

您可以在新的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 / await:

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

关于endTask执行直到响应不成功的原因是因为您在storProduct中处理了error

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

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

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

Promise的catch,与JavaScript中的try/catch效果相同。

关于承诺herecatch有更多参考。

答案 1 :(得分:1)

.then内的任何内容仅在收到成功响应后才会执行

.then(response => {
    this.products.push(response.data.data)
    this.save()
    })

答案 2 :(得分:1)

尝试一下:-

storeProduct() {
  return axios
    .post("products", this.getFormData())
    .then(
      response => this.products.push(response.data.data)
      this.endTask();  //call endtask() here after successfull api call and response back from api
    )
    .catch(
      error => (this.serverErrors = error.response.data.errors.detail)
    )
}