这些是我创建的函数
函数prova在for循环中进行取值然后用我想要显示的内容的值创建各种变量
function prova() {
//Ciclo la fetch per avere solamente i pokemon di settima generazione
for (let index = 1; index < 899; index++) {
const id = index;
fetch(
`https://pokeapi.co/api/v2/pokemon/${id}/`,
{ method: "GET" }
//Attendo la risposta del server
).then(async (response) => {
//do il valore dei vari oggetti alle variabili
let rispostaFetch = await response.json();
let pokemonNumber = rispostaFetch.id;
let pokemonName = rispostaFetch.name.charAt(0).toUpperCase() + rispostaFetch.name.slice(1); //Rendo maiuscola solo la prima lettera
//Do il valore a pokemontypes di un nuovo array contente gli elementi dell'array pokemontypes.type.name con il metodo .map()
let pokemontypes=rispostaFetch.types.map((pokemontypes) => pokemontypes.type.name)
let pokemontype1 = pokemontypes[0];
let pokemontype2 =pokemontypes[1];
Card(pokemontype1,pokemontype2,pokemonNumber,pokemonName);
});
}
}
Card函数创建div,然后是pokGendiv的附属子元素
function Card(pokemontype1,pokemontype2,pokemonNumber,pokemonName) {
//creo dinamicamente un Div con classe .pokemonCard + il risultato della funzione ActiveTypeSecond che dinamicamente mette il tipo di carta (fuoco, erba)
// e metto come id #pokemon#+ la variabile pokemonNumber (il risultato sarà: #pokemon#1 ecc)
let pokemonWrapper = document.createElement('div');
pokemonWrapper.classList.add("pokemonCard", ActiveTypeSecond(pokemontype1.toLowerCase()));
pokemonWrapper.id ='pokemon#'+pokemonNumber;
//All'interno di questo div avrà quanto segue:
pokemonWrapper.innerHTML = `
<div class="pokemonPicture">
<img class="pokemonImage" src="https://assets.pokemon.com/assets/cms2/img/pokedex/full/${ActiveLink(pokemonNumber)}.png" alt="">
</div>
<div class="pokemonName&Number">
<span class ="numeroPokemon">N°${pokemonNumber}</span>
<h3 class ="nomePokemon">${pokemonName}</h3>
</div>
<div class="pokemonTipo">
<ul class="pokemonlista">
<li class="pokemonType">Type:</li>
<span class="separatore"></span>
${Type2Pokemon(pokemontype1,pokemontype2,)}
</ul>
</div>`;
if (pokemonNumber <152) {
const pokGen1 = document.getElementById('PrimaGen')
pokGen1.appendChild(pokemonWrapper)
pagina.appendChild(pokGen1)
}
if (pokemonNumber > 151 && pokemonNumber < 252) {
const pokGen2 = document.getElementById('SecondaGen')
pokGen2.appendChild(pokemonWrapper)
pagina.appendChild(pokGen2)
}
if (pokemonNumber > 251 && pokemonNumber < 387) {
const pokGen3 = document.getElementById('TerzaGen')
pokGen3.appendChild(pokemonWrapper)
pagina.appendChild(pokGen3)
}
if (pokemonNumber > 386 && pokemonNumber < 494) {
const pokGen4 = document.getElementById('QuartaGen')
pokGen4.appendChild(pokemonWrapper)
pagina.appendChild(pokGen4)
}
if (pokemonNumber > 493 && pokemonNumber < 650) {
const pokGen5 = document.getElementById('QuintaGen')
pokGen5.appendChild(pokemonWrapper)
pagina.appendChild(pokGen5)
}
if (pokemonNumber > 649 && pokemonNumber < 722) {
const pokGen6 = document.getElementById('SestaGen')
pokGen6.appendChild(pokemonWrapper)
pagina.appendChild(pokGen6)
}
if (pokemonNumber > 722 && pokemonNumber < 810) {
const pokGen7 = document.getElementById('SettimaGen')
pokGen7.appendChild(pokemonWrapper)
pagina.appendChild(pokGen7)
}
if (pokemonNumber > 809 && pokemonNumber < 899) {
const pokGen8 = document.getElementById('OttavaGen')
pokGen8.appendChild(pokemonWrapper)
pagina.appendChild(pokGen8)
}
}
在各种附件之后,div的顺序是错误的,我该如何修复它?
fetch
调用回调函数(.then(async (response) => {...}
)以异步返回数据。这将导致您的请求(确切地说是898)没有按照您请求的顺序解析,而是在数据发送给您并准备好时解析。
我强烈推荐您可以查看https://javascript.info/promise-basics(或另一个关于承诺的教程)来了解JavaScript中的异步执行和承诺是如何工作的。
如何为你的代码修复这个问题:
- 在请求另一个请求之前等待每个请求。
async function prova() {
for (let index = 1; index < 899; index++) {
const id = index;
const response = await fetch(
`https://pokeapi.co/api/v2/pokemon/${id}/`,
{ method: "GET" }
//Attendo la risposta del server
);
//do il valore dei vari oggetti alle variabili
let rispostaFetch = await response.json();
let pokemonNumber = rispostaFetch.id;
let pokemonName = rispostaFetch.name.charAt(0).toUpperCase() + rispostaFetch.name.slice(1); //Rendo maiuscola solo la prima lettera
//Do il valore a pokemontypes di un nuovo array contente gli elementi dell'array pokemontypes.type.name con il metodo .map()
let pokemontypes=rispostaFetch.types.map((pokemontypes) => pokemontypes.type.name)
let pokemontype1 = pokemontypes[0];
let pokemontype2 =pokemontypes[1];
Card(pokemontype1,pokemontype2,pokemonNumber,pokemonName);
}
}
- 等待所有请求完成后再处理
async function prova() {
// collect returned promises of fetch
let pendingResponses = [];
for (let index = 1; index < 899; index++) {
const id = index;
const promise = fetch(
`https://pokeapi.co/api/v2/pokemon/${id}/`,
{ method: "GET" }
//Attendo la risposta del server
);
pendingResponses.push(promise);
}
// await them all
const responses = await Promise.all(pendingResponses);
// process the returned list of responses
for (const response of responses) {
//do il valore dei vari oggetti alle variabili
let rispostaFetch = await response.json();
let pokemonNumber = rispostaFetch.id;
let pokemonName = rispostaFetch.name.charAt(0).toUpperCase() + rispostaFetch.name.slice(1); //Rendo maiuscola solo la prima lettera
//Do il valore a pokemontypes di un nuovo array contente gli elementi dell'array pokemontypes.type.name con il metodo .map()
let pokemontypes=rispostaFetch.types.map((pokemontypes) => pokemontypes.type.name)
let pokemontype1 = pokemontypes[0];
let pokemontype2 =pokemontypes[1];
Card(pokemontype1,pokemontype2,pokemonNumber,pokemonName);
}
}
- 在添加div后对附加div进行排序。
(这个代码不是我写的)
然而…
同时发出898个API请求不是一个好主意,但是等待它们依次加载也需要很长时间。因此,在实践中,应该使用返回请求列表的API,或者只在用户向下滚动时才扩展显示的HTML列表……但对于训练来说,目前的方式应该足够了。;)这是一个非常有趣的脚本!
欢迎来到异步世界!
您同时发送898个调用,但是每次调用从服务器获得响应时,then(async (response) => { }
内部的代码都会被评估。
但是,您无法控制哪个调用首先到达。如果您希望它们已经按顺序排列,则需要等待第一个调用完成,然后再开始另一个调用。
否则,当你得到每个回应时,你将pokemon插入到正确的位置。
一个更好的端点
如果您需要很多资源(假设超过10个),为每个资源发送单个请求通常不是一个好的做法。如果你控制后端,你最好让一个端点给出多个结果。
据我所知,pokeapi有代端点。
你可能想要使用:)
(例如https://pokeapi.co/api/v2/generation/1
)