How do I loop through multiple pages in an API?

一世执手 提交于 2021-02-11 13:32:17

问题


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?

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

        });      
}

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


回答1:


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;
 }



回答2:


You can do it with async/await functions more easily:

async function fetchAllPages(url) {
    const data = [];

    do {
        let response = fetch(url);
        url = response.next;
        data.push(...response.results);
    } while ( url );

    return data;
}

This way you can reutilize this function for other api calls.



来源:https://stackoverflow.com/questions/57269110/how-do-i-loop-through-multiple-pages-in-an-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!