【问题标题】:Retrieve paginated data recursively using promises使用 promise 递归检索分页数据
【发布时间】:2016-05-10 09:54:07
【问题描述】:

我正在使用一个以分页形式返回数据的函数。所以它将返回最多 100 个项目和一个检索下 100 个项目的键。我想检索所有可用的项目。

我如何递归地实现这一点?递归在这里是一个不错的选择吗?我可以用其他方法不递归吗?

我使用 Bluebird 3x 作为 Promise 库。

这是我想要实现的目标:

getEndpoints(null, platformApplication)
  .then(function(allEndpoints) {
    // process on allEndpoints
  });


function getEndpoints(nextToken, platformApplication) {
  var params = {
    PlatformApplicationArn: platformApplication
  };

  if (nextToken) {
    params.NextToken = nextToken;
  }

  return sns.listEndpointsByPlatformApplicationAsync(params)
    .then(function(data) {
      if (data.NextToken) {
        // There is more data available that I want to retrieve.
        // But the problem here is that getEndpoints return a promise
        // and not the array. How do I chain this here so that 
        // in the end I get an array of all the endpoints concatenated.
        var moreEndpoints = getEndpoints(data.NextToken, platformApplication);
        moreEndpoints.push.apply(data.Endpoints, moreEndpoints);
      }

      return data.Endpoints;
    });
}

但问题是,如果要检索更多数据(请参阅if (data.NextToken) { ... }),我如何将承诺链接起来,以便最终获得所有端点的列表等。

【问题讨论】:

  • 你想什么时候获得下一个 100?是什么触发的?
  • 当有更多可用数据时。如果 data.NextToken 可用,这意味着更多数据可用,所以我必须得到它。
  • 所以您要获取所有端点?
  • 是的。抱歉,这个问题不清楚,更新了。

标签: javascript node.js pagination promise bluebird


【解决方案1】:

递归可能是获取所有端点的最简单方法。

function getAllEndpoints(platformApplication) {
    return getEndpoints(null, platformApplication);
}

function getEndpoints(nextToken, platformApplication, endpoints = []) {
  var params = {
    PlatformApplicationArn: platformApplication
  };

  if (nextToken) {
    params.NextToken = nextToken;
  }

  return sns.listEndpointsByPlatformApplicationAsync(params)
    .then(function(data) {
      endpoints.push.apply(endpoints, data.Endpoints);
      if (data.NextToken) {
          return getEndpoints(data.NextToken, platformApplication, endpoints);
      } else {
          return endpoints;
      }
    });
}

【讨论】:

  • 我明白了。默认参数endpoints = [] 是 ES5 还是 ES6 特性?它可以在 Node.js 版本 0.10.36 下工作吗?
  • 如果您无法访问默认参数 (ES6),则只需从 getAllEndpoints 传入一个空数组或手动检查 getEndpoints 中的未定义。
  • 顺便说一句,推送不应该是这样的:endpoints.push.apply(endpoints, data.Endpoints);,因为我们返回的是endpoints而不是data.Endpoints。只是想确认...
  • 是的。我从问题中复制了它。修好了。
  • 抱歉。我不知道 push.apply 是如何工作的,所以这就是我弄错的原因,但现在我检查了文档并修复了它。感谢感谢您的帮助。它运行良好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-25
  • 1970-01-01
相关资源
最近更新 更多