Javascript using Fetch and pagination, recursive?

前端 未结 2 1534
情书的邮戳
情书的邮戳 2020-12-17 03:36

Hello I\'m new to Javascript and APIs.

But I have an excersise where I should get Data from.

https://swapi.co/api/planets/

The problem is that it doe

相关标签:
2条回答
  • 2020-12-17 04:12

    I had similar needs so I wrote a library called fetch-paginate - here's an example: https://codepen.io/AndersDJohnson/pen/Jqadoz

    fetchPaginate.default("https://swapi.co/api/planets", {
      items: page => page.results,
      params: true
    })
    .then(res => {
      res.data.forEach(planet => {
        const newPlanet = new Planet(planet);
        this.planets.push(newPlanet);
      })
    })
    

    You can get it here: https://unpkg.com/fetch-paginate@3.0.1/bundle.js

    0 讨论(0)
  • 2020-12-17 04:23

    You could recursively create a promise resolve chain. A bit less repetition and you'll know when all planets are loaded when the parent promise resolves.

    function getStarWarsPlanets(progress, url = 'https://swapi.co/api/planets', planets = []) {
      return new Promise((resolve, reject) => fetch(url)
        .then(response => {
            if (response.status !== 200)  {
              throw `${response.status}: ${response.statusText}`;
            }
            response.json().then(data => { 
              planets = planets.concat(data.results);
    
              if(data.next) {
                progress && progress(planets);
                getStarWarsPlanets(progress, data.next, planets).then(resolve).catch(reject)
              } else {
                resolve(planets);
              }
            }).catch(reject);
        }).catch(reject));
    }
    
    function progressCallback(planets) {
      // render progress
      console.log(`${planets.length} loaded`);
    }
    
    getStarWarsPlanets(progressCallback)
      .then(planets => {
        // all planets have been loaded
        console.log(planets.map(p => p.name))
      })
      .catch(console.error);
    
    0 讨论(0)
提交回复
热议问题