Chaining nested asynchronous finds with Node.js monk and MongoDB -


using node.js monk , mongodb, want mimic table join:

  1. do find on collection a
  2. for each result x, find in collection b, , update x
  3. 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

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -