2

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;
            }       
        }
    );

});


console.log(ret);

I got the error as below,

ReferenceError: ret is not defined

Please help me on this!

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.