使用递归的异步数据库调用 [英] Async db calls using recursion
问题描述
我需要递归下降链表数据库树
I have a need to recursively descend a linked list database tree
item 1-> item 2
-> item 3 -> item 4
-> item 5 -> item 6 -> item 7
-> item 8
我的伪代码是
var getItems = function(itemid) {
db.getitem(itemid, function(item) {
item.items.forEach(function(subitem) {
getItems(subitem.id)
})
})
getItems(1)
但是, db.getItem
是一个异步函数
我想将与图表相同结构的JS对象返回给顶级调用者
I would like to return a JS object in the same structure as the diagram to the top-level caller
实现此目标的最佳方法是什么?我不知道前面的结构(即不知道每个项目的项目数或树中任何分支的深度),所以我不知道需要处理的项目数
what is the best way of achieving this ? I don't know the structure up front (i.e. no idea on the number of items per item, or the depth of any branch in the tree) so I have no idea on the number of items I need to process
我尝试了异步库的各种方法,但是似乎没有一个方法可以处理递归
I have tried various methods of the async library, but none seem to deal with recursion
推荐答案
这是强大的并发原语发光的地方.
This is where strong concurrency primitives shine.
承诺让您非常轻松地做到这一点:
Promises let you do this very easily:
// with bluebird this is var getItem = Promise.promisify(db.getitem);
var getItem = function(itemid){
return new Promise(function(resolve, reject){
db.getitem(itemid, function(err, data){
if(err) reject(err);
else resolve(data);
});
});
};
哪个会让你做:
var getItems = function(itemid) {
return getItem(itemid).then(function(item){ // get the first
return Promise.all(item.items.forEach(function(subItem){
return getItems(subitem.id);
});
}).then(function(subItems){
var obj = {};
obj[itemid] = subItems; // set the reference to subItems
return obj; // return an object containing the relationship
});
};
getItems(1).then(function(obj){
// obj now contains the map as you describe in your problem description
});
这是 async
的外观:
var getItems = function(itemid, callback){
db.getitem(itemid, function(err, item){
if(err) return callback(err, null);
async.map(item.items, function(subitem, cb){
getItems(subitem.id, cb);
}, function(err, results){
if(err) return callback(err, null);
var obj = {};
obj[itemid] = result;
return callback(null, obj);
});
});
};
它已经很接近了,但是我认为它比允诺版本好很多.
It gets pretty close but I think it's a lot less nice than the promise version.
这篇关于使用递归的异步数据库调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!