javascript - NodeJS async callback. How to return the list, from a async callback? -
so making database query, posts id, add them list, can return. list returned, before callback has finished.
how prevent being returned before callback has finished?
exports.getblogentries = function(opid) { var list12 =[]; entry.find({'opid' : opid}, function(err, entries) { if(!err) { console.log("adding"); entries.foreach( function(currententry){ list12.push(currententry); }); } else { console.log("eeeerroor"); } //else {console.log("err");} }); console.log(list12); return list12; };
all callback asynchronous, don't have guarantee if run in order have leave them.
to fix , make process "synchronous" , guarantee order executation have two solutions:
- first: make process in nested list:
instead of this:
mymodel1.find({}, function(err, docsmodel1) { callback(err, docsmodel1); }); mymodel2.find({}, function(err, docsmodel2) { callback(err, docsmodel2); });
use this:
mymodel1.find({}, function(err, docsmodel1) { mymodel2.find({}, function(err, docsmodel2) { callback(err, docsmodel1, docsmodel2); }); });
the last snippet above guarantee mymodel2
executed after mymodel1
executed.
- second: use framework async. framework awesome , have several helper functions execute code in series, parallels, whatever way want.
example:
async.series( { function1 : function(callback) { //your first code here //... callback(null, 'some result here'); }, function2 : function(callback) { //your second code here (called after first one) callback(null, 'another result here'); } }, function(err, results) { //capture results function1 , function2 //if function1 raise error, function2 not called. results.function1; // 'some result here' results.function2; // 'another result here' //do else... } );
Comments
Post a Comment