0

如何从 node.js/javascript 回调的值中获取返回值?

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

4 回答 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);
});
于 2013-10-23T10:37:23.240 回答
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);
});
于 2013-10-23T10:37:38.183 回答
0

在 node.js 中,几乎所有回调都在函数返回后运行,所以你可以做这样的事情

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')
        }
    })
}
于 2013-10-23T10:39:25.320 回答
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);
});

使用回调...

于 2013-10-23T10:38:11.090 回答