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?