Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

292
Visualizações
async await not waiting for object to fill axios.get

I have an object called move_dict and am using the method get_learned_by_pokemon() to fill it. In getPokes() I call the get_learned_by_pokemon() and expect move_dict to be filled. However it is empty.

function move(){
    let move_dict = {}
    let db_data = JSON.parse(fs.readFileSync('pokes.json', 'utf8'));
    async function get_learned_by_pokemon(curr_move, move_dict, current_poke){
        response = await axios.get('https://pokeapi.co/api/v2/move/'.concat(curr_move))

        let learned_by_pokemons = []
        for (let k = 0; k < response.data.learned_by_pokemon.length; k++){
            learned_by_pokemons.push(response.data.learned_by_pokemon[k].name)
        }
        // pass
        if (learned_by_pokemons.includes(current_poke)){move_dict[current_poke].pass.push(curr_move)}
        // fail
        else{move_dict[current_poke].fail.push(curr_move)}

    }
    function getPokes(){
        //iterate through all pokemon
        for (let i = 0; i < db_data.length; i++){
            let current_poke = db_data[i].name
            let moves = db_data[i].moves
            move_dict[current_poke] = {pass: [], fail: []}
            //iterate through all moves of pokemon
            for (let j = 0; j < moves.length; j++){
                let curr_move = moves[j]
                //get data on current move
                get_learned_by_pokemon(curr_move, move_dict, current_poke)
            }
        }
    }

    getPokes()
}

I've also used an await before the Axios.get() . I'd like to know why move_dict is not filling and I'd like to overcome this problem without using a setTimeout()

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

It looks like the OP begins with a json file describing pokemons. From the code, it looks like the file contains at least the following...

[
  { name: 'nameA', moves: [ 1, 2, 3, ... ] },
  { name: 'nameB', moves: [ 3, 4, 5, ... ] },
  ...
]

It looks like there's an api endpoint that takes a move ("id or name") and returns, among other things, a list of pokemons that have "learned" that move.

And it looks like the OP aims to produce a dictionary like this...

{
  nameA: { pass: [1, 2, ...], fail: [3, 4, ...] },
  nameB: { pass: [3, 4, ...], fail: [4, 5, ...] },
 ...
}

... where the pass and fail arrays moves found in the input file that either are or are not learned moves according to the api.

Since we don't want to call the api redundantly, and since there might be redundant moves in the input file, it 's worthwhile to create an intermediate structure that associates unique moves in the input the pokemons who have learned them, like this...

{ // key is a move id or name, value is an array of pokemon names
  1 : [ 'nameA', 'nameB', ... ],
  2 : [ 'nameC', 'nameD', ... ],
  ...
}

So here's how I'd describe the idea in code (not compiled or tested)...

async function get_learned_by_pokemon(move){
  const response = await axios.get(`https://pokeapi.co/api/v2/move/${move}`);
  return response.data.learned_by_pokemon.map(p => p.name);
}

async function move() {
  let db_data = JSON.parse(fs.readFileSync('pokes.json', 'utf8'));
  let allMoves = db_data.flat_map(p => p.moves);
  let uniqueMoves = [...new Set(allMoves)];

  // map move ids to pokemons who learned the moves  { moveId: [ 'pokeA', 'pokeB' ...], ...}
  let learnedBy = {}
  for (let move in uniqueMoves) {
    learnedBy[move] = await get_learned_by_pokemon(move);
  }

  // map pokemon names to a pair of arrays indicating if they have learned their moves (pass) or not (fail)
  let move_dict = db_data.reduce((acc, p) => {
    let name = p.name;
    let pass = p.moves.filter(move => learnedBy[move].includes(name));
    let fail = p.moves.filter(move => !learnedBy[move].includes(name));
    acc[name] = { pass, fail };
    return acc;
  }, {});

  return move_dict;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

there are 2 wrong with your code. 1: where do you call getPokes() ? 2: get_learned_by_pokemon is async function so you have to use await if you want to wait for it done

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda