What is the best way to combine arrays fetched from two different Axios API Calls?

Currently, I am faced with a challenge while writing an Express API call. The situation involves making multiple Axios API calls within the same call, and I seem to hit a roadblock.

The concept behind the Express API call is that it receives a query parameter labeled "tags," which can contain any number of tags separated by commas. For example, the URL structure could be:

localhost:5000/api/stuff?tags=tech,history,culture,etc

I have successfully managed to extract the individual tags into an array for further processing.

const theTags = req.query.tags;

const tagsArray = theTags.split(",");

This results in an array like this:

["tech","history","culture","etc"]

However, I've encountered a hurdle at this stage. My task now is to iterate through each tag in the array and perform an Axios API call using each one. Initially, I thought of achieving this using the forEach method. Since each Axios API call should return an array of data related to the specified tag, I believed utilizing the forEach method would help gather all the results effectively:

// Declare an empty array outside the forEach loop.
const sumOfStuffArray = [];

// Begin the forEach loop.    
tagsArray.forEach( (element) => {

   // Make the API call for the current element
   const response = axios.get(`https://api.somewebsite.io/blahblah/stuff?tag=${element}`);
    
   // Retrieve the array from the response data
   const responseArray = response.data.stuff;

   // Iterate through the responseArray using another forEach loop and...
   responseArray.forEach( (anotherElement) => {
      
      // ...append each element of the response array to the sumOfStuffArray
      sumOfStuffArray.push(anotherElement);

   }

}

Unfortunately, my approach has been unsuccessful so far. Every time I attempt to check the length of sumOfStuffArray after the supposed completion of the forEach method, it returns an empty array.

I strongly suspect that I may be overlooking something related to async/await or .then statements, but I'm struggling to identify how to resolve it!

Does anyone have suggestions on how I can consolidate all these array elements into a single array successfully?

Answer №1

There are two important points to consider:

  • axios.get is an asynchronous function that returns a Promise. This means you must wait for its response before accessing the data with response.data.stuff.
  • The forEach method does not support asynchronous behavior - it simply executes a callback for each element without waiting for them to finish. As a result, your result array may be empty because the axios.get calls have not yet completed.

To address this issue, you can wrap your forEach loop in a Promise to ensure it finishes before checking the result array. Additionally, use async/await with axios.get to properly handle its response:

// Initialize an empty array outside of the forEach loop.
const sumOfStuffArray = [];
const waitForEach = new Promise(resolve => {
    tagsArray.forEach(async (element, index, array) => {
       const response = await axios.get(`https://api.somewebsite.io/blahblah/stuff?tag=${element}`);
       const responseArray = response.data.stuff;
       responseArray.forEach( (anotherElement) => {
          sumOfStuffArray.push(anotherElement);
       }

       // Check if forEach has finished
       if (index === array.length - 1) {
           resolve();
       }
    });
}).then(() => {
    console.log(sumOfStuffArray);
});

Alternatively, you can utilize Promise.all with the tagsArray:

const tagsResponses = tagsArray.map(element => axios.get(`https://api.somewebsite.io/blahblah/stuff?tag=${element}`));
Promise.all(tagsResponses).then(responseArray => {
    responseArray.forEach(response => {
        sumOfStuffArray.push(response.data.stuff);
    }
}).then(() => {
    console.log(sumOfStuffArray);
});

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

How can I dynamically retrieve an element from an array in PHP 5?

My array, $configOptions, is composed of arrays. Each individual array ($option) has the following structure: array 'manufacturer1_sender' => string 'general' (length=7) 'manufacturer1_mail' => string '<a hr ...

Fan Animation in CSS

I have three unique images that I would like to animate in a fan-like manner consecutively. I prefer not to merge the images in Photoshop, as I want them to be displayed one after the other. Here is the code snippet (dummy images are used): .bannerimg ...

The JQuery function .remove() will not properly remove dynamically added elements

I am facing an issue when trying to remove an element from a page. Every time I click on a button on the page, it adds a div with the following structure: <div class="holder-div" style="position: relative;display: inline-block;"> ...

Integrate Jade mixins programmatically into an Express application using JavaScript

Within my Express application, I have a file that contains many beneficial Jade mixins. My objective is to utilize this file across various projects by creating an NPM module (hosted in our company's private registry) that will incorporate these mixin ...

Browser-agnostic script proxy

Currently, I am working on client-side Javascript which interacts with JSON web services from a different domain. I've learned that certain browsers don't permit cross-domain scripting, so it's recommended to set up a proxy on my local serve ...

There seems to be an issue with accessing the requested page,

Having some trouble with routing in external files and getting a 'Cannot Get /' error. Can anyone help me figure out what I'm doing wrong? Here is my server.js file: const express = require('express'); const mongoose = require(&a ...

I attempted to combine AngularJS and three.js, but unfortunately, the geometries are not appearing in the render

(I found this example online, but it's not working as expected). I am attempting to incorporate AngularJS for implementing an MVC architecture for three.js files. Despite not encountering any errors during debugging, I am unable to see the rendered ge ...

Leverage JavaScript to retrieve the number of active Ajax requests in JSF

When running Selenium tests using JS, I want to ensure that there are no active Ajax requests. While I can successfully extract the amount of active Ajax requests for jQuery and PrimeFaces, I am facing some issues with JSF. String jsPF = "return PrimeFace ...

Hiding elements on mobile and tablet devices using display:none in html/css

I have a fiddle that is functioning perfectly in desktop view. When clicked, the description box of a product item is displayed at the bottom. See screenshot below: https://i.sstatic.net/yaZDC.png However, in mobile view, all description boxes are automa ...

Manipulating data rows in a table using jquery

I have a button called #add that, when clicked, adds a new row to a table. The last cell of the newly inserted row contains a delete icon that, when clicked, should remove the entire row. I thought I had everything set up correctly, but for some reason, c ...

Encountering a problem with JavaScript when coding an Analog Clock

My attempt to create a simple analog clock has hit a roadblock - the hands of the clock aren't moving. I've focused on coding the seconds hand using CSS for testing purposes, but it's not functioning as expected. Here is the code snippet: ...

JavaScript salary calculation function not functioning properly

Once the user inputs the employee's name and the number of hours they worked on the HTML form, the submit button captures this information and stores it in variables for calculating their pay. The script also factors in overtime pay. Despite feeling l ...

The callback syntax used in the TypeORM Relations decorator is completely baffling to me

Recently, I've been exploring TypeORM and the relationships that can be defined with different decorators. For instance - @OneToOne(type => Profile, profile => profile.user) @JoinColumn() profile: Profile; I'm struggling to understand the ...

Is it possible to maintain line breaks when using ".text" or ".textContent"? Any other options or solutions available? Workarounds to consider?

When trying to copy HTML from one element and paste it as text in another element, I noticed that newlines are not retained in the latest versions of Firefox and Chromium. For instance, if you run the code below (with valid HTML), the output will have the ...

Conceal an absolutely positioned element outside its relatively positioned parent

I have a relative position parent element, <div style="position:relative" id="a"> and within that div, I'm creating some absolute positioned elements using jQuery, <div style="position:absolute;right:0" id="b"> These elements are anima ...

"Selecting an option triggers a change in the dropdown

I am working with 2 select menus: <select name="nama_paket"> <?php do { ?> <option value="<?php echo $row_qpaket['nama_paket']?>"><?php echo $row_qpaket['nama_paket']?></option> <?php } while ( ...

When the span tag is inserted into a contenteditable element on iOS Safari, the cursor automatically shifts to the

One interesting feature allows users to click on a tag and have it added to a contenteditable div. This function works smoothly initially, but when toggling back and forth, the cursor unexpectedly jumps to the end of the div. When a user adds a variable f ...

Using TypeScript to consolidate numerous interfaces into a single interface

I am seeking to streamline multiple interfaces into one cohesive interface called Member: interface Person { name?: { firstName?: string; lastName?: string; }; age: number; birthdate?: Date; } interface User { username: string; emai ...

The Selenium server is currently operational, however, it is encountering issues while attempting to establish a connection with the

I am currently working on setting up test automation using WebdriverIO. After successfully installing all the necessary packages with selenium-standalone, I encountered an issue when trying to start the server. https://i.sstatic.net/7K1O5.png Upon runnin ...

The start date and end date on the Ajax calendar extender have a difference of 60 days

Currently, I am utilizing two AJAX calendar extenders for my project. The first one is for the Start Date and the second one is for the End Date. My requirement is that the end date should always be 60 days ahead of the start date. The date format from ...