通过CRUD API进行分页

时间:2015-08-17 02:48:07

标签: javascript pagination socket.io sails.js

我正在编写一个查询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项获得结果。我希望能够做的是保持循环并接收结果< strong>直到结果数组小于length = 10 (这意味着我们到达了数据集的末尾)。我需要它是异步的,所以我可以从一开始就开始处理数据并更新我每次收到新页面时所做的工作。

1 个答案:

答案 0 :(得分:3)

你想要做的是无限卷轴吗?或者您想要异步调用所有页面并能够在第2页之前接收第3页?阅读这个问题,我理解这是第二个问题。

您不能依赖“,直到结果数组小于长度= 10”,因为您想同时启动所有通话。

您应该第一个查询来检索记录数。然后你就可以知道有多少页面,你可以生成你需要的所有网址并异步调用它们。

它可能看起来像这样(代码没有经过测试):

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 后才需要加载页面 n + 1 你可以依靠results.length < 10

相关问题