简体   繁体   English

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

[英]Creating a promise array for multiple get requests

I have a Vue app that at one point calls a sports feeds API end point to get an array of game ID's so I can iterate thru the ID's to get box scores for individual games. 我有一个Vue应用程序,有一次它调用了体育新闻API端点来获取游戏ID的数组,因此我可以遍历ID以获取各个游戏的得分。 So first in in the main app I do: 因此,首先在主应用程序中执行以下操作:

// 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 ================================= //
    // ================================================================================= //

Now in getBoxScores.js I want create an array of promises and then fulfill them one at a time via axios.all(promises) into the boxscores array and and return it to Vue.js for further processing. 现在在getBoxScores.js中,我想创建一个诺言数组,然后一次通过axios.all(promises)兑现它们到boxscores数组中,然后将其返回给Vue.js进行进一步处理。 It looks like this: 看起来像这样:

// 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;

Problem: Update: See promises[] ok but this.sports_feeds_boxscores still shows as empty on getBoxScores(response) return. 问题:更新:好的,请参见promises [],但是this.sports_feeds_boxscores在getBoxScores(response)返回值上仍然显示为空。 Any ideas? 有任何想法吗? Thanks. 谢谢。

When you retrieve data asynchronously, you need to keep going with the asynchronous pattern and not fall back to synchronous sequences. 异步检索数据时,您需要继续使用异步模式,而不要退回到同步序列。

For example, you access gameIDs synchronously right after you launched an asynchronous request to get it, so that will not work: when executing boxScores(gameIDs); 例如,您在启动异步请求获取gameIDsgameIDs同步访问它,因此将无法正常工作:执行boxScores(gameIDs); the array gameIDs will not yet have been populated. 数组gameIDs尚未填充。

So your code should be organised like this: 因此,您的代码应该像这样组织:

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

Be careful with console.log : it may give the wrong impression that your data is present in the array at the time you made the log. 小心console.log :这可能会给人一种错误的印象,即在您创建日志时,数据已存在于数组中。 This is not necessarily true: the console retrieves content later , at the moment when you expand the array in the console. 这不一定是正确的:当您在控制台中扩展数组时,控制台稍后会检索内容。 It does not always reflect the situation at the time the log was made . 它并不总是反映日志生成时的情况

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM