0

How do I get the return value from inside a value of node.js/javascript callback?

function get_logs(){
    User_Log.findOne({userId:req.user._id}, function(err, userlogs){
        if(err) throw err;
        if(userlogs){
            // logs = userlogs.logs;
            return "hello there is a logs";
        } else {
            return "there is no logs yet..."
        }
    })
}

var logs = get_logs();
console.log(logs);
1
  • You cannot if it's called asynchronously. Use another callback. Commented Oct 23, 2013 at 10:37

4 Answers 4

3

You can't return the result from a function whose execution is asynchronous.

The simplest solution is to pass a callback :

function get_logs(cb){
    User_Log.findOne({userId:req.user._id}, function(err, userlogs){
        if(err) throw err;
        if(userlogs){
            // logs = userlogs.logs;
            cb("hello there is a logs");
        } else {
            cb("there is no logs yet...)"
        }
    })
}

get_logs(function(logs){
    console.log(logs);
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can't. You should instead pass another callback to your function. Something like this:

function get_logs(callback){
    User_Log.findOne({userId:req.user._id}, function(err, userlogs){
        if(err) throw err;
        if(userlogs){
            callback("hello there is a logs");
        } else {
            callback("there is no logs yet...");
        }
    })
}

get_logs(function(arg1) {
   console.log(arg1);
});

Comments

0
function get_logs(callback) {
    User_Log.findOne({
        userId: req.user._id
    }, function (err, userlogs) {
        if (err) throw err;
        if (userlogs) {
            // logs = userlogs.logs;
            callback("hello there is a logs");
        } else {
            callback("there is no logs yet...");
        }
    })
}

get_logs(function (data) {
    console.log(data);
});

Uses callbacks...

Comments

0

In node.js almost all the callbacks run after the function returns , so you can do something like this

function get_logs(){
    User_Log.findOne({userId:req.user._id}, function(err, userlogs){
        if(err) throw err;
        if(userlogs){
            // logs = userlogs.logs;
               do_something(logs)
        } else {
            console.log('No logs')
        }
    })
}

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.