简体   繁体   中英

Is there a better way to use axios to get 2 API results?

I'm creating a ReactJS application, and I have a problem: I'm getting results from 1 api, like bellow:

const perPage = 20;
const offset = (page * perPage) - perPage;
const res = await axios.get(`https://pokeapi.co/api/v2/pokemon?limit=${perPage}&offset=${offset}`);

With the example above, I can return a lot of pokemons.

It returns to me a object with pokemon id and pokemon name. There's another API link, that brings a lot of another informations, like bellow:

https://pokeapi.co/api/v2/PASS_HERE_POKEMON_ID

It brings only one result per time, but a lot of informations.

My question is: What do I do? Should I use the second API and make a loop (with I think is not the best situation), or there's a way to get 20 pokemons (for example), and pass the id of them in the second API, but using axios, promises or another best option?

A possible approach would be:

const getPokemon = (id) => axios.get(`https://pokeapi.co/api/v2/${id}`);

const getPokemons = async (perPage, offset) => {
  const { pokemons } = await axios.get(`https://pokeapi.co/api/v2/pokemon?limit=${perPage}&offset=${offset}`);
  Promise.all(pokemons.map(pok => getPokemon(pok.id)))
    then(results => {
      // array with the response of each call
});
   

More about Promise.all here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM