如何在API中循环浏览多个页面? [英] How do I loop through multiple pages in an API?

查看:68
本文介绍了如何在API中循环浏览多个页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用《星球大战》 API https://swapi.co/我需要输入星际飞船信息,星舰的搜索结果跨越4页,但是get调用每页仅返回10个结果.如何遍历多个页面并获取所需的信息?

I am using the Star Wars API https://swapi.co/ I need to pull in starships information, the results for starships span 4 pages, however a get call returns only 10 results per page. How can I iterate over multiple pages and get the info that I need?

我已经使用fetch api获取星际飞船的第一页,然后将这个10的数组添加到我的totalResults数组中,然后创建了While循环来检查'next!== null'(next是数据中的下一页属性,如果我们正在查看最后一页,即第4页,则next将为null"next" = null)因此,只要next不等于null,我的While循环代码应获取数据并将其添加到我的totalResults数组.我在最后更改了next的值,但它似乎永远循环并崩溃.

I have used the fetch api to GET the first page of starships and then added this array of 10 to my totalResults array, and then created a While loop to check to see if 'next !== null' (next is the next page property in the data, if we were viewing the last page i.e. page 4, then next would be null "next" = null) So as long as next does not equal null, my While loop code should fetch the data and add it to my totalResults array. I have changed the value of next at the end, but it seems to looping forever and crashing.

function getData() {
    let totalResults = [];

    fetch('https://swapi.co/api/starships/')
        .then( res => res.json())
        .then(function (json) {
            let starships = json;
            totalResults.push(starships.results);
            let next = starships.next;

            while ( next !== null ) {
                fetch(next)
                .then( res => res.json() )
                .then( function (nextData) {
                    totalResults.push(nextData.results);
                    next = nextData.next;
                })
            }

        });      
}

代码不断循环,这意味着我的'next = nextData.next;'增量似乎不起作用.

Code keeps looping meaning my 'next = nextData.next;' increment does not seem to be working.

推荐答案

您必须在while循环中 await 响应,否则循环将同步运行,而结果将异步到达,换句话说while循环永远运行:

You have to await the response in a while loop, otherwise the loop runs synchronously, while the results arrive asynchronously, in other words the while loop runs forever:

  async getData() {
     const results = [];
     let url = 'https://swapi.co/api/starships/';

     do {
       const res = await fetch(url);
       const data = await res.json();
       url = data.next;
       results.push(...data.results);
     } while(url)

     return results;
 }

这篇关于如何在API中循环浏览多个页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆