gpt4 book ai didi

javascript - 递归回调

转载 作者:太空宇宙 更新时间:2023-11-04 02:28:13 24 4
gpt4 key购买 nike

所以我试图编写一个函数来获取参数并调用 scan DynamoDB 的方法返回分页结果,并且我还从参数中获取 limit 作为输入,因此我不想递归调用我的扫描函数来获取所有数据,而是希望获取与作为参数传递的 limit 一样多的数据。我尝试了以下代码块,但似乎我的逻辑不正确!你能帮我解决我做错的事情吗?

function scan(params, total, callback) {
dynamo.scan(params, function(err, data) {
if (err) {
callback(err, data);
} else {
if (((!params.Limit || (params.Limit && total.length < params.Limit)))
&& data.Items && data.LastEvaluatedKey) {
params.ExclusiveStartKey = data.LastEvaluatedKey;
(function(data) {
scan(params, data.Items.concat(data.Items), function(err, result) {
data.Items = data.Items.concat(result.Items);
if (result.LastEvaluatedKey)
data.LastEvaluatedKey = result.LastEvaluatedKey;
callback(err, data);
});
} (data));
} else {
callback(err, total); //Here it says undefined is not a function
}
}
});
}

通过以下代码调用:

//params is stuffed with needed parameters for scan method of DynamoDB
scan(params,[],function(err, data){
//Processing data here
})

最佳答案

这是我编写的一些示例代码,如果它适合您的用例或者您有任何疑问,请告诉我。

/**
* This method will scan continue to scan until
* 1) There are no more items (LastEvaluatedKey is null)
* 2) We have retrieved N items from paginated scan
* If we find more than N, we take the first N items.
**/
function scanWithItemLimit(params, n, callback, items) {
db.scan(params, function(err, data) {
if (err) {
callback(err);
} else {
var leftover = n - data.Items.length;
var itemsCopy = items ? items : [];
if (leftover > 0) {
itemsCopy = itemsCopy.concat(data.Items);
var paramsCopy = params;
paramsCopy.ExclusiveStartKey = data.LastEvaluatedKey;
if (params.ExclusiveStartKey) {
scanWithItemLimit(paramsCopy, leftover, callback, itemsCopy);
} else {
callback(err, itemsCopy);
}
} else {
if (n != 0) {
for (var i = 0; i < n; i++) {
itemsCopy.push(data.Items[i]);
}
}
callback(err, itemsCopy);
}
}
});
}

var pfunc = function(err, items) { console.log(err, items); };
params = {TableName: "Table"};
scanWithItemLimit(params, 5, pfunc);

关于javascript - 递归回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29019376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com