0

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. 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. 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. Any ideas? Thanks.

3
  • "I then call the function" : it is important to see all code in one script to see exactly what you mean with phrases like this. But please provide the minimum code necessary to reproduce the problem. Commented Feb 13, 2019 at 15:32
  • Code updated per request. Commented Feb 13, 2019 at 15:43
  • 1
    because ` gameIDs` is fetched asynchronously and you make the call before it is done. The boxScores(gameIDs);` call should be after your loop of setting the gameIDs Commented Feb 13, 2019 at 15:50

1 Answer 1

1

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); the array gameIDs will not yet have been populated.

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. 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.