Perform an action upon a successful completion of an AJAX request using Axios by utilizing the `then()` method for chaining

I'd like to trigger a specific action when an ajax call is successful in axios


    save() {

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

      this.endTask()

    }

When the ajax call to update or store the product succeeds, I want to execute the endTask() function.

I only want the endTask() function to be executed if the ajax call is successful.

How can I achieve this?

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

Answer №1

If you want to implement these methods within a new promise, you can use the example provided below:


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

There are other approaches as well:

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

You can also assign it to a variable:

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

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

Alternatively, you can use async/await:

async save() {
  await this.isUpdateTask ? this.updateProduct() : this.storeProduct()
  // This code will only run if everything happens successfully
  await this.endTask()
}

The reason why the endTask is executed even when the response is not successful is because you handle the error within the storeProduct function.

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

In this case, it is necessary to re-throw the error:

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

The catch method in Promise has the same effect as using try/catch in JavaScript.

For more information on the catch method in promises, you can refer to this link.

Answer №2

Only when a successful response is received, the code inside the .then block gets executed.

.then(result => {
    this.data.push(result.response)
    this.update()
    })

Answer №3

Give this a shot:-

addProductToStore() {
  return axios
    .post("products", this.getProductFormData())
    .then(
      response => {
        this.products.push(response.data);
        this.completeAddingProduct(); // Invoke completeAddingProduct() after a successful API call and receiving a response from the server
      }
    )
    .catch(
      error => (this.serverErrors = error.response.data.errors.detail)
    );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing ESlint: A guide to effectively implementing the globally installed eslint-plugin-vue

For my workflow with Docker, I want to use the linter elint-plugin-vue as a global installation since there may not always be a node_modules folder in my repositories. I previously installed the linter using: sudo npm install -g eslint eslint-plugin-vue ...

What is the best way to create a list from a matrix using JavaScript?

I have an array structured as follows: const input_array= [ ["red", "green"], ["small", "medium"], ["x", "y", "z"] //... can have any number of rows added dynamically ...

"Utilizing Promises in AngularJS Factories for Synchronous API Calls

Attempting to implement synchronous calls using a factory pattern. $scope.doLogin = function (username, password, rememberme) { appKeyService.makeCall().then(function (data) { // data = JSON.stringify(data); debugAlert("logi ...

The inserted button's click event does not trigger the contentEditable DIV

I have a contentEditable DIV that I manage using the directive below: <div class="msg-input-area" [class.focused]="isMsgAreaFocused" contenteditable [contenteditableModel]="msgText" (contenteditableModelChang ...

Tips for filtering only alpha versions, such as those labeled 1.0.0-alpha.*

Is it possible to specifically target -alpha versions of a package using semver and NPM? The common approaches like using 1.0.0-alpha.x or * do not seem to work as expected due to how the version elements are interpreted. The usage of ~1.0.0-alpha also do ...

I encountered an Angular error that is preventing me from updating and uploading images to my Firebase Storage because it is unable to locate the storage bucket

Hey there fellow developers! I'm currently working on a simple Angular app that allows users to upload images to a gallery. However, I've encountered an issue while trying to upload the images to Firebase Storage. I keep getting an error mentioni ...

I'm curious about how I can apply @media queries given that certain phones possess higher resolution than computers

There seems to be a common recommendation to utilize @media queries for adjusting CSS based on whether the user is on mobile or not. However, I'm a bit confused because my phone has a width of 1440p while my computer has 1920p. Should I consider apply ...

Online mailbox feature

My website currently has a "Contact us" form that uses the mailto: function to send emails to my Yahoo account. I am now looking to set up a mailbox directly on my site admin page so I can manage these emails more efficiently by replying or deleting them a ...

Redirecting clients on form submission from the client side

In my cshtml page, I have a script that calls a controller method via jQuery on form submission. It passes data to the method using the values from a datePicker control. Here's an example of the script: $('form').submit(function () { v ...

Angular 1.6 limits the ability to include multiple custom components on a single page

I'm currently working with angular 1.6 and have encountered an issue with two components, config-list and request-dates. Both components function correctly individually on a page, but when I attempt to add both components to the same page, only the s ...

``Why is my setFeatureState function not updating the value in my Mapbox map

I've been attempting to change the stroke of a circle upon clicking it on mapbox. Despite following mapbox's documentation, the values don't seem to update. The console is also clear. t.map.addLayer({ id: id, type: 'circle&apo ...

Generate an array that can be accessed across all components

As someone new to reactjs, I'm trying to figure out how to handle an array of objects so that it can be global and accessed from multiple components. Should I create another class and import it for this purpose? In Angular, I would typically create a ...

Guide: How to transfer the output from MongoDB in Node.js to AngularJS?

Currently, I am using Node.js to query my data from a MongoDB database. However, I am facing an issue where the data is not being sent out as expected when running this particular function. var findIco = function(db, callback) { var cursor = db.collec ...

Increase the Z-Index of the Header above the Material UI Modal Background

Currently, I'm in the process of developing a mobile version of a web application using Material UI. However, I am encountering some challenges when it comes to matching the designs accurately. My approach involves utilizing the MUI App-Bar in conjunc ...

Sidenav Content with all elements having opacity applied

How can I ensure that all page elements have a black background color when the mobile navigation is opened on the left screen, while ensuring that my sidebar and content image do not get overlaid by the black background? Here is my code: function openNav( ...

Employing angularjs alongside a static jsonp file produces results on the first attempt

Currently, I have data being retrieved from a jsonp file within my application. worm.factory('simpleFactory', function ($http, gf) { var simpleFactory = ""; return { getJson: function ($scope) { var url = 'myfile.json?callback=J ...

Unexpected request causes a dilemma during the karma test for an Angular directive

Let's discuss a straightforward directive: 'use strict'; angular .module('app') .directive('ngEmailMask', ngEmailMask); function ngEmailMask() { var directive = { replace: true, restrict: 'EA', ...

"Converting an object to a JSON string using URLSearchParams: A step-by

I am currently working on a piece of code that retrieves all the input types from a form const form = document.querySelector('form'); const data = new URLSearchParams(new FormData(form).entries()); My main concern is how to convert the above ...

I'm having trouble setting up Stripe Elements in PHP. It seems like there's a communication issue between my PHP code and my JS

New to setting up Stripe Elements, I've followed the documentation closely. Installed the necessary JS modules, included the Stripe API, and connected it to the Stripe JS. In my index.php file, PHP script is at the top with HTML and JavaScript below i ...

Is it possible for jQuery UI Tabs to load entire new HTML pages?

In my index.html file, I have set up 3 different tabs. Using the jQuery UI function tabs(), I am attempting to load an HTML page via Ajax. Each HTML page includes the jQuery library and contains the following code: <link type="text/css" href="css/redmo ...