javascript - return value from asynchronous function in Nodejs -
i using nodejs query data mongodb throught mongoose. after data, want on data before responding client. can not return-value. after looking on google, have learned node.js functions asynchronous javascript function (non i/o blocking). try tut (http://www.youtube.com/watch?v=xdw9bk-9pny) not work. below code. myobject valued inside "find()" function , undefined outside "find()" function. should data? thanks!
var person = mongoose.model('person', personschema); var product = mongoose.model('product', productschema); var myobject = new object(); person.find().exec(function (err, docs) { (var i=0;i<docs.length;i++) { product.find({ user: docs[i]._id},function (err, pers) { myobject[i] = pers; console.log(myobject[i]); //return value ok }); console.log(myobject[i]); //return undefined value } console.log(myobject); //return undefined value }); console.log(myobject); //return undefined value app.listen(3000); console.log('listening on port 3000');
the reason you're getting undefined values because find function asynchronous, , can finish @ time. in case, finishing after you're using console.log()
, values undefined when you're accessing them.
to fix problem, can use values inside find function's callback. this:
var person = mongoose.model('person', personschema); var product = mongoose.model('product', productschema); var myobject = new object(); function getdata(docs, callback) { function loop(i) { product.find({ user: docs[i]._id}, function (err, pers) { myobject[i] = pers; if (i < docs.length) { loop(i + 1); } else { callback(); } }); }; loop(0); }; person.find().exec(function(err, docs) { getdata(docs, function() { // myobject has been populated @ point }); });
the data processing has been moved loop waits previous iteration complete. way, can determine when last callback has fired in order fire callback in wrapper function.
Comments
Post a Comment