使用promises递归检索分页数据 [英] Retrieve paginated data recursively using promises
问题描述
我正在使用以分页形式返回数据的函数。所以它将返回最多100个项目和一个键来检索接下来的100个项目。我想检索所有可用的项目。
I'm using a function which returns data in a paginated form. So it'll return max 100 items and a key to retrieve the next 100 items. I want to retrieve all the items available.
我如何以递归方式实现此目的?递归是一个不错的选择吗?我可以在没有递归的情况下以任何其他方式进行吗?
How do I recursively achieve this? Is recursion a good choice here? Can I do it any other way without recursion?
我使用Bluebird 3x作为承诺库。
I'm using Bluebird 3x as the promises library.
以下是我想要实现的内容:
Here is a snippet of what I'm trying to achieve:
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){...}
),如何将promises链接起来,以便最终获得所有端点的列表等。
But the problem is that if there is more data to be retrieved (see if (data.NextToken) { ... }
), how do I chain the promises up so that in the end I get the list of all endpoints etc.
推荐答案
递归可能是获取所有端点的最简单方法。
Recursion is probably the easiest way to get all the endpoints.
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;
}
});
}
这篇关于使用promises递归检索分页数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!