我正在尝试循环遍历 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 时,甚至只需要一个请求即可获取所有结果,但当然,您仍然应该使用此代码,以便它可以获取第 2 页,以防有一天超过 1000 页)。
关于javascript - 循环访问通过 URL 链接的 API 结果页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60676166/