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
- Function loops through JSON array('arr') containing credentials, and with each object / credential set inside, logs in to API and returns values.
- These values should be collected to one array, which will contain all of the returned objects.
- Function returns this array after finished.
CodePudding user response:
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]
})
