Home > Net >  Asynchronous data returning in random order
Asynchronous data returning in random order

Time:01-31

I'm using the pokeapi to get the data of 151 pokemon. Since the API doesn't have a route to get all pokemon, I have to send 151 asynchronous get requests (one for each pokemon).

Despite the data being queried in order, I'm noticing the pokemon are returning in random order, with a different order each time. What are some strategies I can use to prevent this and keep them ordered in order of the requests (#1 - #151)? I'm assuming this is due to the asynchronous nature of the requests. Async/await could be useful but I haven't been able to implement it successfully here.

pokedex.component.html:

<div >
    <div *ngFor="let pokemon of pokemons" >
        <div>
            <img src="{{ pokemon.sprites.front_default }}"/>
        </div>
        <span style="display:flex;">#{{pokemon.id}}</span>
        <span>{{pokemon.name | titlecase}}</span>
    </div>
</div>

pokedex.component.ts:

  constructor(public _httpService: HttpService) { }

  ngOnInit(): void {
     this.getPokemon();
  }

  pokemons = [];

  getPokemon() {
    this._httpService.getPokemon().subscribe( async (data) => {
      data.results.forEach((pokemon)=>{this.getPokemonDetails(pokemon.name)});
    });
  }

  getPokemonDetails(pokemon) {
    this._httpService.getPokemonDetails(pokemon).subscribe((data)=>{
      this.pokemons.push(data);
    });
  }

http.service.ts:

constructor(private http: HttpClient) { }

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

  getPokemon(): Observable<any> {
    return this.http.get(`${this.pokemonsUrl}?limit=151`);
  }

  getPokemonDetails(name): Observable<any> {
    return this.http.get(`${this.pokemonsUrl}/${name}`);
  }

CodePudding user response:

You could skip the usage of async inside the subscription, and use RxJS enter image description here

  •  Tags:  
  • Related