【问题标题】:Creating a promise array for multiple get requests为多个 get 请求创建一个 promise 数组
【发布时间】:2019-07-07 11:57:25
【问题描述】:

我有一个 Vue 应用程序,它有时会调用体育提要 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[] ok 但 this.sports_feeds_boxscores 在 getBoxScores(response) 返回时仍显示为空。有任何想法吗?谢谢。

【问题讨论】:

  • "I then call the function" :重要的是查看 one 脚本中的所有代码,以准确了解此类短语的含义.但请提供重现问题所需的最少代码。
  • 根据请求更新代码。
  • 因为 `gameIDs` 是异步获取的,并且您在完成之前进行了调用。 boxScores(gameIDs);` 调用应该在设置 gameIDs 循环之后

标签: javascript promise async-await axios


【解决方案1】:

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

例如,您在启动异步请求以获取gameIDs 后立即同步访问它,因此这将不起作用:执行boxScores(gameIDs); 时,数组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

小心console.log:它可能会给人一种错误的印象,即您的数据在您创建日志时就存在于数组中。这不一定是真的:当您在控制台中展开数组时,控制台稍后会检索内容。它并不总是反映制作日志时的情况

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2019-10-18
    • 2014-05-12
    • 2023-01-26
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    相关资源
    最近更新 更多