Guide for linking together multiple Axios calls to ensure they execute in sequence and enable each call to access the data obtained from the preceding call

Hey everyone, I have a unique challenge that requires your help. So, I'm working with an array of items and I need to make an Axios post for each item in the array. The catch is that each item relies on data returned from the previous one, so they must be executed synchronously. Here's where it gets tricky - I don't actually know how many items will be in the array. If I had that information, I could handle it like this:

let my_array = [34, 44, 72];

axios.post(
    'url-to-get-data',
    {
        post_data_1: my_array[0]
    }
    ).then(res => {
        axios.post(
            'url-to-get-data',
            {
                post_data_1: my_array[1],
                post_data_2: res.data
            }
            ).then(res => {
                 //Third axios post.....
            }
            ).catch();
        }
        ).catch();

If you have any ideas or suggestions on how I can tackle this issue effectively, please share them!

Answer №1

Are you wondering how to link together multiple async tasks of an unknown length?

If using promises and recursion:

let asyncDec = count => Promise.resolve(count - 1);

let handler = count => {
  console.log('handled', count);
  if (count)
    return asyncDec(count).then(handler)
};

asyncDec(10).then(handler);

If using await/async:

let asyncDec = async count => count - 1;

let main = async () => {
  let count = 10;
  while (count >= 0) {
    console.log('handled', count)
    count = await asyncDec(count);
  }
};
main();

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

Load as soon as the browser is launched

I have developed a unique button that utilizes JavaScript to display the server status through an API. However, I am facing an issue where the server status does not automatically load when the browser is opened for the first time. You need to manually cli ...

Outputting Javascript Strings via PHP

Currently, I am utilizing a web service that generates tables through JavaScript functions. However, I am in need of the table to be generated in plain HTML format instead. One potential solution to achieve this is by transferring the JavaScript string t ...

Vue3 JS Component: A Component Staying the Same

I am currently working on a component that retrieves data from an API. The data returned from the API is in the form of an array with various details. One of the values in this array specifies the type of component that needs to be rendered, while all the ...

modify brand information through the use of javascript and customizable settings

In the default setting, I want all product details to be displayed. If the option value matches the product's brand name (b_name), then I want to display the corresponding details. Let's consider a list of products with their details: Samsung ...

Problems with scrolling in Firefox when using Three.JS

Is anyone else experiencing issues with three.js? I have a simple demo of a spinning cube with varying rotational velocity using arrow keys, mouse, or touch input. Everything works perfectly in Chrome, but the textures are spliced and not mapped correctly ...

How to access JavaScript files from "bower_components" instead of "node_modules" using webpack

With the utilization of main-bower-files in my Gulp compilation tasks, it is not feasible for me to use webpack to require modules from the node_modules directory as it would interfere with the processing of CSS, images, and fonts in my current asset sys ...

Is it possible to create dynamic animations with SVG files?

I am currently in the process of coding my website, and I came up with an exciting idea to animate my navigation bar within an SVG container. With its naturally wavy design, I aim to achieve a sweeping wave effect similar to the intro animation on Discord. ...

Node.js Axios is encountering the ERR_FR_TOO_MANY_REDIRECTS error, yet there is no infinite loop detected when using curl, a browser, or

Currently, I'm attempting to retrieve the URL below using Axios in NodeJS: However, when utilizing Axios for this task, I encounter the error ERR_FR_TOO_MANY_REDIRECTS. Upon closer inspection of the issue, it appears that there may be an encoding pro ...

The looping functionality in Swiperjs is not working properly for sliders

Encountering some issues with the loop setting for swiper. The problem is that it stops sliding before entering a second loop, always halting at a certain point. I have never worked with swiper before, so I am unsure if this is the intended behavior or not ...

Currently focused on developing vertical sliders that can be manipulated by dragging them up or down independently

https://i.stack.imgur.com/NgOKs.jpg# I am currently working on vertical sliders that require dragging up and down individually. However, when I pull on the first slider, all sliders move together. The resetAllSliders button should also work independently, ...

What could be causing the "Cannot POST /api/" error to occur when attempting to submit a form?

Having issues with my basic website and struggling to find a solution. As a complete beginner in this field, I am stuck and need some guidance. Accessing http://localhost:3000/class/create works perfectly fine when running the server. However, trying to a ...

(Vue.js) The icon fails to be applied

<link rel="icon" href="/static/icons/apple-touch-icon.png" type="image/x-icon"> <link rel="icon" type="image/png" sizes="32x32" href="/static/icons/apple-touch-icon.png"> <link rel="icon" type="image/png" sizes="16x16" href="/static/ ...

To validate any object, ensure that it contains a specific key before retrieving the corresponding value in typescript

When looking at a random object, my goal is to verify that it follows a certain structure. obj = {WHERE:{antherObject},OPTIONS{anotherObject}} Once I confirm the object has the key using hasProperty(key), how can I retrieve the value of the key? I thoug ...

Checkbox Hierarchy: Children marked as either Checked or Unchecked based on parent selection

Hello, I have a form that contains nested checkboxes on three levels. Using jQuery, I am trying to check/uncheck all the children when I check a parent level... and if any of the children are unchecked, uncheck the parent as well. I have attempted this m ...

Learn how to trigger an HTTP exception after a failed command in a saga with NestJS CQRS

Currently utilizing the NestJS CQRS pattern to handle interactions between User and UserProfile entities within my system. The setup consists of an API Gateway NestJS server along with dedicated NestJS servers for each microservice (User, UserProfile, etc. ...

The `sameAs` validator in vuelidate does not function properly when using the `not` validator with a computed value

I am facing an issue with getting the not validator to work in conjunction with a computed sameAs value. While I am using the term "computed" here, I am not completely certain if it is the most accurate term. Hopefully, alongside the reproducible code pr ...

Verifications in the realm of javascript

I created a custom form in Django which is functioning correctly. However, when I try to implement JavaScript validation, the validations do not seem to work as expected. I am looking to validate the form using JavaScript. Although it displays the alert me ...

Stop images from being stored in the database instead of text characters

Using a proxy, I attempt to parse some HTML. One of the elements is retrieved using jQuery: var site = 'http://www.kartabu.com/pl/index.php?filter=random' var url = 'http://localhost/taboo.blue-world.pl/admin/proxy.php?url=' + encodeUR ...

The attempt to establish a WebSocket connection to 'ws://localhost:4000/graphql' was unsuccessful:

Encountering the Websocket failed to Connect error on both the client and server sides (shown in image below) has left me puzzled for the past 2 days. I have not made any other Websocket configurations apart from the one specified in the apollo client. Any ...

Initiating and pausing an Interval using a single button

I'm attempting to create a JavaScript-based chronometer that starts and stops when a single button is clicked. However, I am struggling to figure out how to properly implement the setInterval function to achieve this functionality. Below is my current ...