0

so im fetching some data from the PUBG Api, and pushing the needed data into an array called "playerRecentStats", but whenever i try to take this array out of the function i get an undefined or empty result, i can read it from some points on the function but whenever i try to read it out of the fetch or general function it doesnt work.

Here is the code for context

let playerRecentStats = [];
    function recentMatchesPerformance() {
      
      last10Matches.map((match) => {
        fetch(
          `https://api.pubg.com/shards/${playerPlatform}/matches/${match.id}`,
          options
        )
          .then((response) => response.json())
          .then((data) => {
            data.included.forEach((player) => {
              if (player.type == 'participant') {
                if (player.attributes.stats.name == playerName) {
                  playerRecentStats.push({
                    kills: player.attributes.stats.kills,
                    dmgDone: player.attributes.stats.damageDealt,
                    knocks: player.attributes.stats.DBNOs,
                    date: data.data.attributes.createdAt,
                  });
                }
              }
              // console.log(playerRecentStats); This reads here!
            });
            // console.log(playerRecentStats); This does not read here!
          });
      });
      return playerRecentStats; // This is returning an empty array!
    }
    recentStats = recentMatchesPerformance();
    // I want to read the playerRecentStats Array here.
    console.log(playerRecentStats); // Empty Array
    console.log(recentStats); // Empty Array

Hopefully you can help me, thanks.

CinemaClub
  • 69
  • 6
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Jared Smith Apr 30 '22 at 19:29
  • All http client engines (including "fetch") in javascript work asynchronously. This means that the next line will not wait for processing. They all have event handling methods (for "fetch" it's "then") to process the result. – E.H. Apr 30 '22 at 19:42

0 Answers0