0

I have this app that makes call to API and extracts gameIDs from returned object.

/* jshint ignore:start */
        axios
          .get(
            `https://api.mysportsfeeds.com/v1.2/pull/nba/${seasonName}/scoreboard.json?fordate=${
              date.yesterday
            }`,
            config
          )
          .then(response => {
            this.sports_feeds_data = response.data.scoreboard.gameScore;
            return this.sports_feeds_data;
          })
          .then(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;
          })
          // Now call getBoxScores to retrieve box scores
          .then(gameIDs => {
            test = getBoxScores(gameIDs); // **No value returned**
            console.log(test);
          })
          .catch(error => {
            console.log(error);
            this.errored = true;
          });
        /* jshint ignore:end */

Now we go into getBoxScores and get boxScores:

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

/* jshint ignore:start */
const getBoxScores = gameIDs => {
  gameIDs.forEach(function(item) {
    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
        }
      })
    );
  });

  axios
    .all(promises)
    .then(function(results) {
      results.forEach(function(response) {
        boxScores.push(response.data.gameboxscore);
      });

      return boxScores;
    })
    .then(function(boxScores) {
      console.log(boxScores);
      return boxScores;
    });
};
/* jshint ignore:end */

module.exports = getBoxScores;

Problem: 1. Unable to return boxScores array from to getBoxScores.js.

  1. When I console.log test I get nothing in array. console logging boxScores I see my resolved promises with values. Any insight appreciated. Thanks...

Updated resolution:

.then(async gameIDs => {
        // Check if boxscores have been retrieved on previous tab click
        this.sports_feeds_boxscores.nba =
          this.sports_feeds_boxscores.nba || (await getBoxScores(gameIDs));
      })

And in getBoxScores:

// axios.all returns a single Promise that resolves when all of the promises passed
// as an iterable have resolved. This single promise, when resolved, is passed to the
// "then" and into the "values" parameter.
await axios.all(promises).then(function(values) {
  boxScores = values;
});

return boxScores;


};


    module.exports = getBoxScores;

The above update now works...

Alan
  • 1,067
  • 1
  • 23
  • 37
  • `getBoxscores` should *return* the result of that final chain starting with `axios.all(promises)`. Then consumers would use the promise it returns. See the linked questions for details. – T.J. Crowder Feb 13 '19 at 18:49
  • You seem to be *adding* to your arrays every time `getBoxScores` is called. Those arrays should be *inside* the `getBoxScores` function, or if it's meant to run just once when that file is loaded, you should export the result of calling it (the promise). – T.J. Crowder Feb 13 '19 at 18:50
  • 1
    Side note: Any time you start with `someArray = [];` and then do `anotherArray.forEach(...)` and do `someArray.push(something)` unconditionally within the `forEach` callback, it's more idiomatic to use `map`: `someArray = anotherArray.map(entry => { /*...*/ return something; });` – T.J. Crowder Feb 13 '19 at 18:51
  • Thanks for assist. Question: Why does call in main body work without async/await? Shouldn't async activities in getBoxScores() cause error when I console.log(this.sports_feeds_boxscores). – Alan Feb 14 '19 at 16:42
  • The resolution you've added to the question is incorrect. You need to return the *promise* from `axios.all(promises)`. Then the calling code needs to consume the promise. See the [first linked duplicate](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) for details. – T.J. Crowder Feb 14 '19 at 17:02
  • Thanks. I think I finally got it figured out. When I check in Vue debug the boxscores are in the virtual DOM. – Alan Feb 16 '19 at 01:30

0 Answers0