async await不等待对象填充axios.get



我有一个名为move_dict的对象,并使用get_learned_by_pokemon()方法填充它。在getPokes()中,我调用get_learned_by_pokemon(),并期望move_dict被填充。然而,它是空的。

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()
}

我还在Axios.get()之前使用了await。我想知道为什么move_dict不填充,我想克服这个问题,而不使用setTimeout()

看起来OP以一个描述口袋妖怪的json文件开始。从代码中,看起来该文件至少包含以下内容…

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

看起来有一个api端点接受移动("id或名称")并返回,除其他事项外,有"学习"移动。

看起来OP的目标是制作这样的字典…

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

…根据api,在输入文件中找到的通过和失败数组的移动是或不是学习到的移动。

由于我们不想冗余地调用api,并且由于输入文件中可能存在冗余的移动,因此值得创建一个中间结构,将输入中的唯一的移动与学习它们的口袋妖怪联系起来,就像这样…

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

所以这是我如何在代码中描述这个想法(未编译或测试)…

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;
}

你的代码有两个错误。1:你在哪里调用getPokes() ?2: get_learned_by_pokemon是async函数,所以如果你想等待它完成,你必须使用await

最新更新