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
时将执行该功能) 最佳答案
Promise.all(listOfPromises)
将解析为一个包含listOfPromises
中每个promise解析结果的数组。
要将其应用于您的代码,您需要类似(pseudocode)的代码:
Promise.all(matchlist.map(match => getMatchDetails(...)))
.then(listOfMatchDetails => {
// do stuff with your list!
});