Master the art of linking multiple axios calls together in a single promise

I've been delving into Axios and promises lately, trying to grasp the concept. It seems like I'm on the right track, but there are definitely some mistakes in my approach. My javascript method is supposed to return a promise, within which I have an Axios post request with two chained .then methods. Whenever the initial post fails, I encounter an unsightly error in the console:

Unhandled promise rejection ReferenceError: "reject is not defined"
. I suspect that nesting the .catch methods might be the issue here, and perhaps it should simply be post.then.then.catch.

Moreover, I am puzzled as to why the itemInformation is not being returned in the response within the second .then block. Can anyone shed light on this?

Check out the relevant Javascript code (the addToCartVue method is invoked first):

addToCartVue(itemData) {
  let vm = this;
  return new Promise((resolve, reject) => {

    vm.buildDataString(itemData);

    axios.post(POST_ENDPOINT, {
        data: vm.dataString
      },
      {
        /*headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        }*/
      }).then(response => {
      return vm.updateCartInfo(vm.dataString, itemData.addToCartParameters.itemId, vm.selectedStoreId, vm.quantity);
    }).then(response => {
      if (itemData.addToCartParameters.showLB) {
        vm.emitGlobalEvent('addToCart::open', itemData);
        resolve(response);
      }
    }).catch(error => reject(error));
  }).catch(error => reject(error));
}, // end of addToCartVue method

buildDataString(itemData) {
  // irrelevant code that builds quantity and dataString variables

  vm.quantity = quantity;
  vm.dataString = dataString;
}, // end of buildDataString method

updateCartInfo(dataString, itemId, selectedStore, quantity) {
  axios.get(GET_ENDPOINT, {
    params: {
      data: dataString
    }
  }).then(response => {
    cartDropDown.populateCartDropDown(response);
    const addedItem = response.addedItem;
    const basketInfo = response.basketInfo;

    let productQuantity = quantity;
    if (addedItem.quantity > -1) {
      productQuantity = addedItem.quantity;
    }

    const itemInformation = {
      "itemId": itemId,
      "selectedStore": selectedStore,
      "addedItem": addedItem,
      "basketInfo": basketInfo,
      "displayValues": null,
      "quantity": productQuantity,
      "isCustomProduct": false
    };

    return itemInformation;
  }).catch(err => error => reject(error));
} // end of updateCartInfo method

Answer №1

One possible solution could be adding the 'return' keyword where it seems to be missing.

Consider inserting 'return' in two key places:

 return axios.post(POST_ENDPOINT...

Additionally, make sure to include 'return' inside the updateCartInfo function as well:

return axios.get(GET_ENDPOINT,...

Cautiously note that wrapping your code within a Promise object might not be necessary, as axios already returns a promise. This can help prevent reject reference errors.

let vm = this;
vm.buildDataString(itemData);
return axios.post(POST_ENDPOINT, {
    data: vm.dataString
  },
  {
    /*headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    }*/
  }).then(response => {
  return vm.updateCartInfo(vm.dataString, itemData.addToCartParameters.itemId, vm.selectedStoreId, vm.quantity);
}).then(response => {
  if (itemData.addToCartParameters.showLB) {
    vm.emitGlobalEvent('addToCart::open', itemData);
    return response
  }
})

Lastly, ensure you catch any potential errors in the call to addVue():

addVue().then(data => console.log(data).catch(err => console.log(err))

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

What is the best way to post an image using nodejs and express?

Recently, I've been working on a CMS for a food automation system and one feature I want to incorporate is the ability to upload pictures of different foods: <form method="post" enctype="multipart/form-data" action="/upload"> <td>< ...

Can the execution of a jQuery Timeout function be halted if a user navigates away from the page?

Implementing a timer in a view with jQuery: var timer, myDiv = $('#mydiv'); $(document).on('mousemove', function(ev) { var _self = $(ev.target); clearTimeout(timer); if (_self.attr('id') === 'mydiv' || ...

What is the reason for the initial DOM operation taking significantly longer than subsequent ones?

Why is the first operation much more despite the subsequent manipulation of the DOM being practically identical in time when both are written with the realization in JS and jQuery? Link to Javascript source // ES5 // Sending a message function sendMessa ...

When attempting to retrieve data saved to req.session with express-session from a different endpoint, the data appears to be

While working on my project with express-session, I encountered a peculiar issue. I am saving the currently logged in user to the session, but when I try to access the currentUser key on the get route, I find that the value is an empty object. Strangely, i ...

"Enhance Your Form with JQuery Date Selector for Multiple Input

Using JQuery and ASP.Net C#3.0. Here is the script I am working with: <script> $(document).ready(function () { $("[id$=txtHiddenDate]").datepicker({ showOn: "button", buttonImage: "../../images/calendar-icon.gif", ...

Experiment with utilizing dynamic imports within the useEffect hook

I've been working on testing a custom hook I developed that involves dynamically importing @vimeo/player. The key snippet from the useVideoPlayer hook is as follows: useEffect(() => { async function setup() { const { default ...

Disabling animations in Reactjs with CSSTransition and Group Transition

Currently, I am experimenting with REACTJS to build a basic app featuring Transitions. In my project file, I have imported CSSTransitions and Group Transition. However, when attempting to implement CSSTransition for specific news items, the animations are ...

Node.JS, R, and Python are used for intensive computing tasks such as identifying when a callback function has finished executing and

My Node.js REST API exposes endpoints that trigger R and Python scripts for complex computations. Prior to executing these scripts, I must first identify the callback, assign a unique ID to it, and quickly send back the ID to the consumer. The consumer wil ...

Validating Angular Forms within a NgFor loop

Consider the scenario where there is a form implemented as shown below: <form #form="ngForm"> <div *ngFor="let action of member_plan.actions"> <div class="container"> <h4 class="text-sm-center black mb-3">{{ ...

The es6 object class is not defined

Hey there, I'm currently working on a simple pong game and encountering an issue with passing the player object into drawPlate. It seems to be printing the information correctly, but then I get hit with an Uncaught TypeError exception. The data print ...

Creating concise AngularJS Controllers for form functionality

While working on a web project with AngularJS, I've observed that most of my form controllers share similar structures. For instance, the only difference between my login controller (as shown below) and a reset password controller is that instead of $ ...

Discover Repetitive Entries within the Gridview employing Javascript

I need assistance with a specific requirement. My Gridview has two columns: Name of Model Model Description Model A Model A Description Edit Update Cancel Model B Model B Description Edit Update Cancel Model C Model C Description Edit Update C ...

Transferring data from Node.js server to React client with axios communication

I have a project in the works that involves tracking chefs and their new recipes. I am developing a simple frontend application where users can input a chef's username, which will then be sent to the backend for scraping several cooking websites to re ...

Create an array of various tags using the ngRepeat directive to iterate through a loop

I'm familiar with both ngRepeat and forEach, but what I really need is a combination of the two. Let me explain: In my $scope, I have a list of columns. I can display them using: <th ng-repeat="col in columns">{{ col.label }}</th> This ...

Transferring numerous hefty JSON documents at once from React Native to Node.js

I am facing a challenge while attempting to upload multiple large JSON files from React-native to Node.js. The files are successfully uploaded, except for when the file size is large, causing it not to upload in one attempt. My suspicion is that: Due t ...

Tips for sending JSON information to refresh Highcharts Pie chart

Currently, I am attempting to utilize AJAX to send a year value to my server. The server will then retrieve information from a database regarding various countries' economies for that specific year. Subsequently, I intend to use this data to update th ...

Attempting to retrieve data from local server 3000 to local server 3001 resulted in an unexpected termination of the input stream

After attempting to make a GET request to the Serp API directly from a React application, I discovered that it was not possible. To work around this issue, I created a local server and implemented the necessary logic. After testing the server using Postman ...

Instead of using colons, display the separation of hours, minutes, and seconds with underscores

Currently, I am utilizing moment.js to retrieve the present date and time with the intention of formatting it in the specific format below 'MMMM Do YYYY, h:mm:ss a' Unfortunately, the problem arises as the delineation between hours, minutes, and ...

Issue with findOneAndUpdate: document is not being updated and the function is returning null

Hello everyone, I am diving into the world of mongodb and mongoose for the first time. I could really use some assistance with a problem that has me stuck. Here's the issue at hand: Below is a snippet of my code where I have an addressSchema along w ...

The IsArray() function in IE8 encounters an issue where it expects an error object

I am interested to know why IE8 is having trouble with this line of code: if (isArray(obj)) When I check in the IE8 javascript console, I see the following: >>obj {...} >>typeof(obj) "object" >>Object.prototype.toString.call(obj) "[obj ...