Reputation: 1301
function createDataSet(username, region, champion, amount) {
var dataArray = []; //what I want to return, if possible with .map()
return getUserId(username, region) //required for getUserMatchlist()
.then(userId => {
getUserMatchlist(userId, region, champion, amount); //returns an array of objects
})
.then(matchlist => {
matchlist.forEach(match => {
getMatchDetails(match.gameId.toString(), region) //uses the Id from the matchlist objects to make another api request for each object
.then(res => {
dataArray.push(res); //every res is also an object fetched individually from the api.
// I would like to return an array with all the res objects in the order they appear in
})
.catch(err => console.log(err));
});
});
}
I'm trying to send data that I fetched from multiple apis to my frontend. Fetching the data isn't a problem, however, using .map()
didn't work and from what I've read doesn't work well with promises. What is the best way for me to return that object? (function will be executed when a get request is received and dataArray
will be sent back)
Upvotes: 0
Views: 28
Reputation: 3496
Promise.all(listOfPromises)
will resolve to an array containing the resolved result of each promise in listOfPromises
.
To apply that to your code, you would want something like (pseudocode):
Promise.all(matchlist.map(match => getMatchDetails(...)))
.then(listOfMatchDetails => {
// do stuff with your list!
});
Upvotes: 2