我正在尝试遍历API结果的所有页面,该结果以URL返回下一页:
const api_url= 'https://wger.de/api/v2/exercise/?format=json&page=29';
async function getExercises(){
const response = await fetch(api_url);
const data = await response.json();
data.results.forEach( item => console.log(item.name))
}
getExercises();
您将如何做呢?
您可以使用while
循环:
async function getExercises () {
let url = 'https://wger.de/api/v2/exercise/?format=json'
while (url) {
const res = await fetch(url)
const data = await res.json()
for (const item of data.results) {
console.log(item.name)
}
url = data.next
}
}
// By the way, always catch errors here, otherwise they will become unhandled rejections!
// This is assuming that this call happens outside of an async function.
getExercises().catch(e => console.error('Failed to get exercises', e))
而且,我还做出了有根据的猜测,您可以指定一个limit
参数,对其进行测试,并且看来它可以工作。因此,您可以通过设置更高的限制来减少所需的请求数,例如https://wger.de/api/v2/exercise/?format=json&limit=1000
(现在有685个结果,因此限制为1000个,它甚至只需要一个请求即可获取所有结果,但是当然,您仍然应该使用此代码,以便在一天中有1000个以上的情况下获取第2页)。
您可以使用递归来实现。
let currentPage = 1;
const limit = 5;
const apiURL = 'https://wger.de/api/v2/exercise?format=json';
const getExercises = async () => {
const res = await fetch(`${apiURL}&page=${currentPage}`);
const data = await res.json();
// you can remove the limit
if (data.results.length && currentPage <= limit) {
currentPage++;
data.results.forEach(val => console.log(val.name));
getExercises();
} else {
return;
}
}
getExercises();