从Javascript中的回调函数返回

时间:2013-10-23 10:35:16

标签: javascript node.js

如何从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 个答案:

答案 0 :(得分:3)

您无法从执行异步的函数返回结果。

最简单的解决方案是传递回调:

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

答案 1 :(得分:0)

你做不到。您应该将另一个回调传递给您的函数。像这样:

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

答案 2 :(得分: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);
});

使用回调......

答案 3 :(得分: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')
        }
    })
}