Home > Back-end >  Using return data from an async function, in another function
Using return data from an async function, in another function

Time:10-06

I'm doing a little data analysis from chess.com data

I have this code

const getUsernames = async function() {
  let response = await chessAPI.getCountryPlayers('RE')
  names = [...response.body.players]
  //console.log(names)
  return names
}

const grabPlayerScores = async function() {
  let players = getUsernames()
  // let playerStats = [];
  for (i = 0; i = players.length; i  ) {
    let data = await chessAPI.getPlayerStats(i)
    console.log(data)
  }
}

grabPlayerScores();

I can't get the other function to await the return of the first. I know I should use promises or structure my other function differently but I'm still getting the hang of these types of functions.

CodePudding user response:

You need to add another await in your grabPlayerScores function to wait for getUsernames to finish.

const grabPlayerScores = async function() {
  // Add an 'await' here
  let players = await getUsernames();

  for(let i = 0; i = players.length; i  ) {
    let data = await chessAPI.getPlayerStats(i)
    console.log(data)
  }
}

CodePudding user response:

I changed bit in your code,

const grabPlayerScores = async function () {
  let players = await getUsernames();
  for (i = 0; i = players.length; i  ) {
    let data = await chessAPI.getPlayerStats(players[i]);
    console.log(data)
  }
}
  • Related