通过URL链接的API结果页面循环[重复]

问题描述 投票:0回答:2

我正在尝试遍历API结果的所有页面,该结果以URL返回下一页:

enter image description here

            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();

您将如何做呢?

javascript json api loops
2个回答
1
投票

您可以使用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页)。


0
投票

您可以使用递归来实现。

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();
© www.soinside.com 2019 - 2024. All rights reserved.