简体   繁体   English

有没有更好的方法来使用 axios 获得 2 个 API 结果?

[英]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:我正在创建一个 ReactJS 应用程序,但我遇到了一个问题:我从 1 api 得到结果,如下所示:

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.它返回给我一个带有口袋妖怪 ID 和口袋妖怪名称的 object。 There's another API link, that brings a lot of another informations, like bellow:还有另一个 API 链接,它带来了很多其他信息,如下所示:

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? 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或其他最佳选择?

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更多关于Promise.all 在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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