代码之家  ›  专栏  ›  技术社区  ›  cubefox

从链式承诺返回映射数组

  •  0
  • cubefox  · 技术社区  · 7 年前
        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() 不起作用,从我所读到的内容来看,与承诺不符。对我来说,归还物品的最佳方式是什么?(函数将在收到get请求时执行,并且 dataArray

    1 回复  |  直到 7 年前
        1
  •  2
  •   Michael Pratt    7 年前

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

    要将其应用到代码中,您需要(伪代码):

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