Return from callback function in Javascript

前端 未结 4 594
时光说笑
时光说笑 2021-01-27 06:21

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,          


        
4条回答
  •  梦如初夏
    2021-01-27 06:29

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

提交回复
热议问题