kiasaty
kiasaty

Reputation: 187

do something when an ajax call is successful in axios - chaining then() in axios

I'm trying to do something when an ajax call is successful in axios

    save() {

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

      this.endTask()

    }

if the ajax call to update or store the product is successful, I want to run the endTask() function.

I don't want the endTask() function to be run when the ajax call is not successful.

how can I do that?

the store function:

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

Upvotes: 1

Views: 1384

Answers (3)

Fuechter
Fuechter

Reputation: 1240

You can call this methods inside a new promise like this below example:


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

Have other ways to do also:

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

Or assign to a variable:

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

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

Or with async/await:

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

And about the endTask execute until when response is not successful, is because you treat the error inside the storProduct.

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

So, in this case, is necessary re-throw the error again:

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

The catch of Promise, have same effect of try/catch from javascript.

Have more reference about catch on promise here.

Upvotes: 2

Raj Gohel
Raj Gohel

Reputation: 1102

Try this:-

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

Upvotes: 1

Michael
Michael

Reputation: 5048

Anything inside the .then is only executed when a successful response is received

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

Upvotes: 1

Related Questions