How to get the callback function return values in NodeJS
Below is the code uses mongoskin for mongodb access with nodejs. How do i access the callback function return value from the outside?
app.get('/', function(req, res) {
var ret = db.collection('counters').findAndModify(
{_id: 'messagetransaction'},
[],
{$inc : {next: 1}},
true,
true,
function(err, counter) {
if (err) {
throw err;
}else{
console.log(counter.next);
return counter.next开发者_StackOverflow;
}
}
);
});
console.log(ret);
I got the error as below,
ReferenceError: ret is not defined
Please help me on this!
The problem is you never know when the callback is going to fire; its asynchronous. Therefore you don't want to have anything wait on the result. What you should do is instead of returning a value, you should invoke a function, passing the value, and that function should do what you want it to do with the result.
精彩评论