[英]Is there a better way to use axios to get 2 API results?
我正在创建一个 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}`);
通过上面的示例,我可以返回很多口袋妖怪。
它返回给我一个带有口袋妖怪 ID 和口袋妖怪名称的 object。 还有另一个 API 链接,它带来了很多其他信息,如下所示:
https://pokeapi.co/api/v2/PASS_HERE_POKEMON_ID
它每次只带来一个结果,但信息量很大。
我的问题是:我该怎么办? 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或其他最佳选择?
一种可能的方法是:
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
});
更多关于Promise.all
在这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.