Chaining nested asynchronous finds with Node.js monk and MongoDB -
using node.js monk , mongodb, want mimic table join:
- do find on collection a
- for each result x, find in collection b, , update x
- return updated list of results
the asynchronous nature of database commands in monk giving me trouble. initial code. doesn't work because second call find
returns promise immediately, , results in xs
sent in response before can updated.
var db = require('monk')('localhost/mydb'); db.get('collection').find({}, function(e,xs) { xs.foreach(function(x){ coll_b.find({a_id:x._id}, function(e,bs) { a['bs'] = bs; }); }); res.json({'results':as}); });
i feel should use promise chaining here, cannot figure out how it. appreciated.
i think solved in way, inspired this answer:
var db = require('monk')('localhost/mydb'); // initial find db.get('collection').find({}, function(e,xs) { // inner finds list of functions return promises var tasks = xs.map(function(x){ return function() { return coll_b.find({a_id:x._id}, function(e,bs) { a['bs'] = bs; }); } }); // chain tasks var p = tasks[0](); // start first 1 for(var = 1; < tasks.length; i++) p = p.then(tasks[i]); // after tasks done, output results p.then(function(_x){ res.json({'results':xs}); }); });
i still feel code minimised using chain()
, @ least works expected.
note: realise performing second find each result not efficient, that's not concern here.
Comments
Post a Comment