【问题标题】:Iterate through Paginated API Results in Javascript在 Javascript 中遍历分页 API 结果
【发布时间】:2020-03-03 14:51:03
【问题描述】:

我正在用 Javascript 编写一个函数,该函数进行提取并接收分页的结果(正如预期的那样,结果很长)。

结果将包含一个“next_page”,它是下一页结果的获取主页 url。理想情况下,我想循环并不断获取,直到我到达结果的末尾,也就是当“next_page”=null 时。

当 next_page 不为空时,我似乎无法弄清楚如何遍历结果。似乎发生的事情是我陷入了无限的while循环。

欢迎提出任何建议。我在下面提供了伪代码。

while(next_page!=null){
   fetch(apiUrl)
  .then(res=>res.json())
   .then(data => {
    apiUrl=data["next_page]
   }
  if(apiUrl == null)
    {
      res.send(data)
      break;
    }
}

我在想while循环会让我迭代直到没有next_page(也就是当它为空时)。似乎它只是无限循环而没有命中 fetch,因为 apiUrl 没有设置为 null。

【问题讨论】:

    标签: javascript reactjs pagination


    【解决方案1】:

    你可以试试下面的函数,而不是while循环

    // Initial API Call
    fetchData('http://localhost/test1.php?page=1');
    
    // Create the function for API Call 
    function fetchData(apiUrl){ 
      fetch(apiUrl)
        .then(res=>res.json())
        .then(data => {
          console.log(data);
          apiUrl = data['next_page'];
          // Check next API url is empty or not, if not empty call the above function 
          if(apiUrl != '' && apiUrl != null){
              fetchData(apiUrl);
          }
      })
    }
    

    【讨论】:

      【解决方案2】:

      这可能是因为您正在阅读data["next_page"]apiUrl,但随后在循环中检查了不同的变量。应该改为while(apiUrl) { ...

      【讨论】:

      • 试试console.log(data["next_page"])看看有什么
      猜你喜欢
      • 2016-07-08
      • 2015-02-07
      • 2010-11-16
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-30
      • 1970-01-01
      相关资源
      最近更新 更多