Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

269
Views
Fetching data from multiple API endpoints

Background information

I'm working on a project where I need to fetch data from multiple API endpoints, each with it's own credentials. Right now, I'm mapping through an JSON array containing all of the different credentials, and pushing the returned data to an empty array, like show below.

Code

const fetchData = async () => {

dataArray = [];

// Loop through all objects in the array, 'arr' contains all of the different credentials. 
arr.map(async (obj) => {

// Defining info to access API. 

// Authenticating to API. 

// Fetching data from API.

// Returns one array containing one or multiple objects. (data).

/* Pushing first object of the array to dataArray. I would also like to push all objects  
   if there is more than one! */
dataArray.push(data[0]);
});

// Return array after mapping through arr.
return dataArray;
};

module.exports = { fetchData };

Problem

If I do it this way, function only returns an empty array. So it doesn't wait the first part of the function(mapping through arr) to finish.

On the other hand, if I declare empty array (dataArray= [];) on higher level outside fetchData function, it returns fetched values. But if its done this way, array doesn't never reset and fills up with data.

How can I fix this? Or is there a better way to do this altogether?

Desired result

  1. Function loops through JSON array('arr') containing credentials, and with each object / credential set inside, logs in to API and returns values.
  2. These values should be collected to one array, which will contain all of the returned objects.
  3. Function returns this array after finished.
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Use Promise.all in fetchData function

let arr=["credential 1","credential 2","credential 3"]


let requestArr = []

for (var i = arr.length - 1; i >= 0; i--) {
    //for example we use axios to send request
    requestArr.push(axios(`request with releted credential`))
}

//here we got all the promised request array
let responseArr = await Promise.allSettled(requestArr)
responseArr.then(res => {
// res is a arr of all individual request
[res1, res2]
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!