我正在使用以分页形式返回数据的函数。所以它将返回最多100个项目和一个键来检索接下来的100个项目。我想要检索所有可用的项目。
我如何以递归方式实现这一目标?递归是一个不错的选择吗?我可以在没有递归的情况下以任何其他方式进行吗?
我正在使用Bluebird 3x作为承诺库。
以下是我想要实现的内容的片段:
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) { ... }
),我如何将承诺链接起来,以便最终获得所有端点的列表等。
答案 0 :(得分:5)
递归可能是获取所有端点的最简单方法。
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;
}
});
}