获取的项目顺序混乱

Messy order on items fetched

我正在尝试在 html 上显示 10 个宠物小精灵...我有时得到的是最终结果的混乱顺序。就像 id=5 的口袋妖怪出现在第二位,依此类推。

我假设我的错误来自函数调用之间的某种异步。

我对异步函数有点陌生,所以不要对我评价不好哈哈...

所以我的代码是这样的:

pokemonAPI = "https://pokeapi.co/api/v2/pokemon?offset=0&limit=10";

async function getPokemonList(url){
    let resp = await fetch(url);
    if (resp.ok){
        let list = await resp.json();
        list.results.forEach(pokemon => {
            getPokemonData(pokemon.url);
        });
    }
}

然后getPokemonData函数:

async function getPokemonData (url){
    let resp = await fetch(url);
    if (!resp.ok){
        throw new Error(`HTTP error!, fetching pokemon data. Status: ${resp.status}`);
    }
    let data = await resp.json();
    fillContent(data);
}

fillContent 函数使用 innerHTML 将新卡片添加到我的容器 div 元素。

最终结果(并非总是如此)如下所示:Display error

对我哪里出错有什么建议吗?

感谢@A_A的帮助

Nvm the first comment, I was a bit confused. A simple for loop instead of forEach and await getPokemonData(pokemon.url) should do the trick

所以实际上我在 forEach 中一个接一个地调用我的函数 getPokemonData(pokemon.url) 而没有等待它完成获取我正在发送的 url。

for (let pokemon of list.results){
   await getPokemonData(pokemon.url);
}

将其更改为一个简单的循环并等待我的函数结束解决了它