通过 CRUD 分页 API

paginating through a CRUD API

我正在编写一个将查询 CRUD 网络的客户端 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页?看了题目,明白是第二种。

你不能依赖 "until the results array is less than 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+1 =]n 你可以依赖 results.length < 10