【问题标题】:loop through API results pages that are linked by URL [duplicate]循环通过 URL 链接的 API 结果页面 [重复]
【发布时间】:2020-03-14 05:46:26
【问题描述】:

我正在尝试遍历 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();

你会怎么做呢?

【问题讨论】:

    标签: javascript json api loops


    【解决方案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 甚至只需要一个请求即可获得所有结果,但当然您仍应使用此代码,以便它获取第 2 页,以防有一天超过 1000 )。

    【讨论】:

    • 我明白了,我从来不知道limit参数!非常感谢您的解释!
    【解决方案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();
    

    【讨论】:

    • 嗯,有什么限制?请求/调用的数量是多少?
    • 无需递归,可以使用常规循环 - 将其添加为答案
    猜你喜欢
    • 2019-07-02
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    相关资源
    最近更新 更多