Javascript 使用 Fetch 和分页,递归? [英] Javascript using Fetch and pagination, recursive?

查看:23
本文介绍了Javascript 使用 Fetch 和分页,递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我是 Javascript 和 API 的新手.

Hello I'm new to Javascript and APIs.

但是我有一个练习,我应该从中获取数据.

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

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

问题在于它不会一次列出所有行星,因此 URL 仅显示前 10 个条目,而 https://swapi.co/api/planets/?page=2 显示下一个等等.

The problem is that it doesn't list all the planets at once so that URL only shows the first 10 entries while https://swapi.co/api/planets/?page=2 shows the next and so on.

这是我当前的代码,它可以工作,但我不认为我会按照预期进行,所以我想知道您将如何解决这个问题.

This is my current code, it works but I don't think I'm going as I'm supposed to so I wonder how you would solve this problem.

https://codepen.io/indiehjaerta/pen/QQXVJX

var starWarsAPI = new StarWarsAPI();
starWarsAPI.Initialize();

function StarWarsAPI()
{
    this.planets = new Array();

    this.Initialize = function()
    {
        this.LoadPlanets("https://swapi.co/api/planets");
    }

    this.LoadPlanets = function(aURL)
    {

        fetch(aURL).then(
            function (response) 
            {
                if (response.status !== 200) 
                {
                    console.log('Looks like there was a problem. Status Code: ' + response.status);
                    return;
                }

                response.json().then(
                    data => this.LoadPlanetsRecursive(data)
                );
            }.bind(this)
        ).catch(function (err) 
        {
            console.log('Fetch Error :-S', err);
        });
    }

    
    this.LoadPlanetsRecursive = function(aData)
    {

        for (let planet of aData.results)
        {
            let newPlanet = new Planet(planet);
            this.planets.push(newPlanet);
        }

        if (aData.next != null)
        {
            fetch(aData.next).then(
                function (response) 
                {
                    if (response.status !== 200) 
                    {
                        console.log('Looks like there was a problem. Status Code: ' + response.status);
                        return;
                    }
    
                    response.json().then(
                        data => this.LoadPlanetsRecursive(data)
                    );
                }.bind(this)
            ).catch(function (err) 
            {
                console.log('Fetch Error :-S', err);
            });
        }
    }
this.PresentPlanetsInHTML = function()
{
    
}
}

function Planet(aPlanet)
{
    this.name = aPlanet.name;
    console.log(this);
}

第二个问题是我应该把我的PresentData"放在哪里,这样我就知道所有的行星都被加载了,而不是当它们被添加到数组时 1 个 1.

2nd question is where I should put my "PresentData" so I know that all planets have been loaded and not 1 by 1 when the're added to the array.

推荐答案

您可以递归地创建一个 promise 解析链.少一点重复,当父承诺解决时,你就会知道所有行星何时被加载.

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

这篇关于Javascript 使用 Fetch 和分页,递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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