JavaScript Fetch & Push Array 返回 “undefined”

我正在用普通的javascript编写一个应用程序。我遇到了一个问题,在将150个对象放入数组时,数组中的某些对象未定义。当我控制台.log对象之前将它们推入数组之前,它们很好,并且所有150个对象都显示出来。但是,当我将它们推送到阵列时,有些是未定义的,有些确实被成功推送。我的理解是,这可能是一个序列问题的时间问题,对于某些对象,它们可能尚未完全获取,但推送到数组已经发生。有没有办法确保它们被排序,以便数组仅在完全成功获取对象后才被推送?感谢您的帮助。


const fetchPokemon = function () {


  const pokemons = [];


  for ( let i=1; i <= 150; i++) {

      const url = `https://pokeapi.co/api/v2/pokemon/${i}`;

      fetch(url).then( res => { return res.json(); })

      .then( data => {

          const pokemon = {

              name: data.name,

              id: data.id          

          };

          pokemons.push(pokemon);

          console.log(pokemon);

          console.log(pokemons[i]);

      });

  }

};


fetchPokemon();

输出 - 根据未定义的数组元素,页面的不同重新加载而变化


app.js:17 undefined

app.js:16 {name: "dragonite", id: 149}

app.js:17 undefined

app.js:16 {name: "mewtwo", id: 150}

app.js:17 undefined

app.js:16 {name: "kingler", id: 99}

app.js:17 {name: "electrode", id: 101}

app.js:16 {name: "aerodactyl", id: 142}

app.js:17 {name: "zapdos", id: 145}

app.js:16 {name: "dratini", id: 147}

app.js:17 {name: "kingler", id: 99}


慕桂英3389331
浏览 116回答 2
2回答

慕尼黑8549860

您的问题是,虽然每个单独的请求都是异步的,但您在所有 150 个请求完成之前都会返回。在下面的 for 循环中,不是链接到请求并立即推送,而是将 promise 推送到数组中。然后,在循环之后,返回一个 Promise,一旦请求了所有 150 个 Promise 并将其推送到数组中,该 Promise 就会解析。fetchrequestspokemonsconst fetchPokemon = function() {&nbsp; const pokemons = [];&nbsp; const requests = [];&nbsp; for (let i = 1; i <= 150; i++) {&nbsp; &nbsp; const url = `https://pokeapi.co/api/v2/pokemon/${i}`;&nbsp; &nbsp; const prom = fetch(url).then((r) => r.json());&nbsp; &nbsp; requests.push(prom);&nbsp; }&nbsp; return new Promise((resolve) => {&nbsp; &nbsp; Promise.all(requests)&nbsp; &nbsp; &nbsp; .then((proms) =>&nbsp; &nbsp; &nbsp; &nbsp; proms.forEach((p) => pokemons.push({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name: p.name,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; id: p.id&nbsp; &nbsp; &nbsp; &nbsp; }))&nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; .then(() => resolve(pokemons));&nbsp; });};fetchPokemon().then(console.log);

海绵宝宝撒

在这里发布这个,作为一个更简单,更简洁和最好的例子使用异步/等待。并行 fetch,具有迭代第一个顺序就绪 fetch 响应的功能。即:如果前 25 个 fetch 完成,它将按顺序迭代前 25 个,而无需等待后一个 125。const fetchPokemon = async function() {&nbsp; const pokemons = [];&nbsp; for (let i = 1; i <= 150; i++) {&nbsp; &nbsp; const url = `https://pokeapi.co/api/v2/pokemon/${i}`;&nbsp; &nbsp; const data = fetch(url).then(res => res.json())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.then( ({name, id}) => ({name, id}) );&nbsp; &nbsp; pokemons.push(data);&nbsp; }&nbsp; for await (const pokemon of pokemons) {&nbsp; &nbsp; console.log(pokemon);&nbsp; }&nbsp; // or if you need to use the index:&nbsp; for (let i = 0; i < pokemons.length; i++) {&nbsp; &nbsp; console.log(await pokemon[i]);&nbsp; }};fetchPokemon();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript