简体   繁体   English

从 Javascript 中的回调函数返回

[英]Return from callback function in Javascript

How do I get the return value from inside a value of node.js/javascript callback?如何从 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);

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

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);
});
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... 使用回调...

In node.js almost all the callbacks run after the function returns , so you can do something like this 在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')
        }
    })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM