asynchronous数据库使用recursion调用
我有一个需要recursion下降链接列表数据库树
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
是一个asynchronous函数
我想返回一个JS对象与图的结构相同的顶级调用者
达到这个目标的最好方法是什么? 我不知道前面的结构(即不知道每件物品的数量,或树中任何分支的深度),所以我不知道我需要处理的物品数量
我已经尝试了asynchronous库的各种方法,但似乎没有处理recursion
这是强壮的并发基元发光的地方。
承诺让你很容易做到这一点:
// 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); }); }); };
它变得非常接近,但我认为它比承诺版本更好。