通过CRUD API分页

paginating through a CRUD API

本文关键字:分页 API CRUD 通过      更新时间:2023-09-26

我正在编写一个客户端,将查询CRUD web API。我将用socket.io.get('/api')。问题是:我想对结果进行分页,这样我就可以在客户端仍在接收数据时开始显示内容。

来自API的结果为JSON,如

[
  {
    "id": "216754",
    "date": "2015-07-30T02:00:00.000Z"
  },
  {
    "id": "216755",
    "date": "2015-08-30T02:00:00.000Z"
  }
]

api允许我构造一个URL查询,我可以在其中限制每个结果数组的大小。所以我可以做一个像/api&skip=10&limit=10这样的查询,它会给我从项目10到项目19的结果。我想要能够做的是保持循环并接收结果,直到结果数组小于length = 10(这将意味着我们到达了数据集的末尾)。我需要它是异步的,这样我就可以从头开始处理数据,并在每次收到新页面时更新我所做的工作。

你想要无限滚动吗?还是希望异步调用所有页面,以便能够在页面2之前接收页面3 ?读了这个问题,我明白是第二个。

你不能依赖"直到结果数组小于length = 10",因为你想同时启动所有的调用。

您应该执行第一个查询来检索的记录数。然后,您将能够知道有多少页面,您可以生成所需的所有url并异步调用它们。

它可能看起来像这样(代码未测试):

var nbItemsPerPage = 10;
socket.io.get(
  '/api/count',  // <= You have to code the controller that returns the count
  function(resCount) {
    nbPages = resCount / nbItemsPerPage;
    for (var i=0; i<nbPages; i++) {
      // Javascript will loop without waiting for the responses
      (function (pageNum) {
        socket.io.get(
          '/api',
          {skip:nbItemsPerPage*pageNum, limit=nbItemsPerPage},
          function (resGet) {
            console.log('Result of page ' + pageNum + ' received');
            console.log(resGet);
          }
      )(i);  // <= immediate function, passing "i" as an argument
             // Indeed, when the callback function will be executed, the value of "i" will have changed
             // Using an immediate function, we create a new scope to store pageNum for every loop
    }
  }
)  

如果你想存档的是一个无限滚动的页面,那么你必须加载页面n+1只有在你收到页面n的内容后,你可以依靠results.length < 10