首页 > 解决方案 > 从链式承诺返回映射数组

问题描述

    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()没有用,而且从我读过的内容来看,promise 不能很好地工作。我返回该对象的最佳方式是什么?(函数会在收到get请求后执行,并dataArray返回)

标签: javascriptnode.jsasynchronous

解决方案


Promise.all(listOfPromises)将解析为一个数组,其中包含listOfPromises.

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

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

推荐阅读