从链式承诺返回映射数组

时间:2019-01-04 15:48:34

标签: javascript node.js asynchronous

    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发回时执行该功能)

1 个答案:

答案 0 :(得分:2)

Promise.all(listOfPromises)将解析为一个包含listOfPromises中每个promise解析结果的数组。

要将其应用于您的代码,您需要使用类似(伪代码)的方法:

Promise.all(matchlist.map(match => getMatchDetails(...)))
    .then(listOfMatchDetails => {
        // do stuff with your list!
    });