为多个get请求创建一个Promise数组

时间:2019-02-13 15:29:31

标签: javascript promise async-await axios

我有一个Vue应用程序,有一次它可以调用Sports Feeds API端点来获取游戏ID的数组,因此我可以遍历ID来获取各个游戏的得分。所以首先在主应用中,我要做:

// vue.js
         /* jshint ignore:start */
    axios
      .get(
        `https://api.mysportsfeeds.com/v1.2/pull/nba/${seasonName}/scoreboard.json?fordate=${
          date.yesterday
        }`,
        config
      )
      .then(async response => {
        this.sports_feeds_data = await response.data.scoreboard.gameScore;
        return this.sports_feeds_data;
      })
      .then(async response => {
        // Fill up array with all the game ID's for today's games
        // This will be used to retrieve the Box Scores later
        response.forEach(function(item, index) {
          gameIDs[index] = item.game.ID;
        });

        return gameIDs;
      })
      .then(response => {
        this.sports_feeds_boxscores = getBoxScores(response);
      })
      .catch(error => {
        console.log(error);
        this.errored = true;
      });
    /* jshint ignore:end */

    console.log("Here are boxScores" + this.sports_feeds_boxscores);================================================================================= //
    // ============================ End Get NBA Scores ================================= //
    // ================================================================================= //

现在在getBoxScores.js中,我想创建一个promise数组,然后一次通过axios.all(promises)将它们兑现到boxscores数组中,然后将其返回给Vue.js进行进一步处理。看起来像这样:

// getBoxScores.js

const axios = require("axios");

let boxScores = [];
let promises = [];

/* jshint ignore:start */
const getBoxScores = gameIDs => {
  console.log(gameIDs);
  gameIDs.forEach(function(item) {
    console.log(item); // nothing output
    console.log("Im in forEach"); // nothing output
    let myUrl = `https://api.mysportsfeeds.com/v1.2/pull/nba/2018-2019-regular/game_boxscore.json?gameid=${item}`;

    promises.push(
      axios({
        method: "get",
        headers: {
          Authorization:
            "Basic NzAxMzNkMmEtNzVmMi00MjdiLWI5ZDYtOTgyZTFhOnNwb3J0c2ZlZWRzMjAxOA=="
        },
        url: myUrl,
        params: {
          teamstats: "none",
          playerstats: "PTS,AST,REB,3PM",
          sort: "stats.PTS.D",
          limit: 3,
          force: true
        }
      })
    );
  });



    console.log(promises);
  axios.all(promises).then(function(results) {
    results.forEach(function(response) {
      boxScores.push(response.data.gameboxscore);
    });
    return boxScores;
  });
};
/* jshint ignore:end */

module.exports = getBoxScores;

问题:   更新:好的,请参见promises [],但是this.sports_feeds_boxscores在getBoxScores(response)返回值上仍然显示为空。有任何想法吗?谢谢。

1 个答案:

答案 0 :(得分:1)

当您异步检索数据时,您需要继续使用异步模式,而不能退回到同步序列。

例如,您在启动一个异步请求以获取它后立即同步访问gameIDs,这样就无法正常工作:执行boxScores(gameIDs);数组{{1 }}尚未被填充。

因此,您的代码应这样组织:

gameIDs

请谨慎使用axios.get(url, config) .then(async response => { .... }) .then(async response => { .... return gameIDs; // <-- better practice to drive the output through the chain }) .then(boxScores); // <-- call it asynchronously! .catch(error => { ... }); // Whatever code comes here should not expect anything from the above // asynchronously retrieved data. It will not yet have been retrieved :这样做可能会给人一种错误的印象,即在您创建日志时,数据已存在于数组中。这不一定是正确的:在控制台中扩展数组时,控制台将检索内容以后。它并不总是反映日志制作时的情况。。