0

I'm trying to use PokeAPI with JS.

I can get Pokeman information successfully and display it, but not in the right order.

I used a forEach loop and would like to wait until I add the first Pokeman and then add the second...

I've discovered await and I tried to use it but I can't do it. Can someone help me please?

Here is my JS code :

var url = 'https://pokeapi.co/api/v2/pokemon/';

fetch(url)
  .then(function(response) {
    return response.json();
  })
  .then(function(response) {
    response.results.forEach(element => {
      var url = 'https://pokeapi.co/api/v2/pokemon/' + element.name;
      fetch(url)
        .then(function(response) {
          return response.json();
        })
        .then(function(response) {
          addPokemon(response.name, response.sprites.front_default, response.types[0].type.name, response.height, response.weight);
        })
    });
  })
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
auvoybe
  • 11
  • 2

4 Answers4

0

You can use 'for' loop instead of forEach.

for (let i = 0; i < length; i++) {
  const poke = await fetch(...);
}
Alex Shinkevich
  • 348
  • 1
  • 5
0
Promise.all(response.results.map(...)).then(
Qwertiy
  • 19,681
  • 15
  • 61
  • 128
0

It looks like you're using Promises but not the async/await syntax.

You can use a forEach with async await, since the code can be written in a way that "looks" synchronous.

Right now, you're just executing multiple Promises one after another within the forEach loop. I would probably chain the promises together and then await Promise.all() to do something useful after they have all fulfilled.

0

First of all, why do you use double ".then()" clause? After each "fetch()" in the first ".then()" clause you return the response, and after, in the second ".fetch()" clause you use the same response for manipulating over the same data. Remove unnecessary ".then()" clauses first. Secondly, could you please share the inner part of the "addPokemon()" function? You claim that data is loaded in the wrong order. I assume the problem is in the way you "add" the data to some unknown array. Please, clarify those points. Most probably, your problem is there.

Niyazi Babayev
  • 120
  • 2
  • 9