开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜