javascript - Find inside callback of another find (...), how to escape from callback hell? -


(first: i'm sorry, don't speak english well!)

i wanna return results of 3 finds in 1 array. code (next) running well, i'm in callback hell!

_schema   .static('retrieveall', function(cb) {     query = {};     this.find(query, function(err, data) {       if(err) {         cb(err, null);         return;       }        if(data)         = data;       else         = [];        _storesmodel.find(query).select('contact address').exec(function(err, data) {         if(err) {           cb(err, null);           return;         }          if(data) {           = data.reduce(function(coll, item) {             coll.push(item);             return coll;           }, all);         }          _customersmodel.find(query).select('contact address').exec(function(err, data) {           if(err) {             cb(err, null);             return;           }            if(data) {             = data.reduce(function(coll, item) {               coll.push(item);               return coll;             }, all);           }            cb(null, all);                   });       });     });   }); 

i've find inside find inside find. there anyway improve this?

solution:

_schema .static('retrieveall', function(cb) { var model = this;

_async.parallel(   { contacts: function(cb) {       model.find({}).exec(cb);     }   , stores: function(cb) {       _storesmodel.find({}).select('contact address').exec(cb);     }   , costumers: function(cb) {       _costumersmodel.find({}).select('contact address').exec(cb);     }   } , function(err, data) {   if(err) {     cb(err, null);     return   }    var ret = [];   if(data.contacts.length > 0) {     ret = ret.concat(data.contacts);   }   if(data.stores.length > 0) {     ret = ret.concat(data.stores);   }   if(data.costumers.length > 0) {     ret = ret.concat(data.costumers);   }    cb(null, ret); }); 

take @ npm async. great library of different patterns can used on node.js.

you want use waterfall if there chronological priority or parallel pattern if can execute in parallel.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -