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));
});
});
}
我正在尝试将从多个API获取的数据发送到前端。提取数据不是问题,但是,使用.map()
无效,并且从我阅读的内容来看,不能很好地满足诺言。我退还该物件的最佳方法是什么? (将在收到获取请求并将dataArray
发回时执行该功能)
答案 0 :(得分:2)
Promise.all(listOfPromises)
将解析为一个包含listOfPromises
中每个promise解析结果的数组。
要将其应用于您的代码,您需要使用类似(伪代码)的方法:
Promise.all(matchlist.map(match => getMatchDetails(...)))
.then(listOfMatchDetails => {
// do stuff with your list!
});