0

Expected output: "x is 2" Actual output: "x is undefined"

app.js

var x = db_Save(req.session.user);
console.log('x is ' + x);

dbFile.js

var db_Save= function (user) {

    // return 2; /* 'x is 2' would print;

    console.log('function returns "undefined" before following');
    userProfile.find({Email: profileInstance.Email}, function(err, doc){
        console.log('prints after "x is undefined"');
        return 2; // does not get returned  
    });
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Sangram Singh
  • 7,161
  • 15
  • 50
  • 79
  • 1
    You're passing an anonymous function as a callback to another function - where exactly do you expect its return value to go to? – Anthony Grist Sep 13 '13 at 13:37
  • 1
    See [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call). Even though you're probably not doing ajax in there, the problem and its solutions are the same. – Bergi Sep 13 '13 at 13:38
  • 1
    Node.js asynchronous, and you need to understand concept of being event-driven, rather than functional in the way execution is happening. – moka Sep 13 '13 at 13:43

2 Answers2

3

Use a callback function :

db_Save(req.session.user,function(x){
    console.log('x is ' + x);
});

var db_Save= function (user,callback) {
    userProfile.find({Email: profileInstance.Email}, function(err, doc){                                
        callback(2);
    });
};
mguimard
  • 1,881
  • 13
  • 14
1

userProfile.find is asynchronous which means it gets kicked off but does not return 2 until after your console.log has fired. Your callback is this function:

 function(err, doc){                              
    console.log('prints after "x is undefined"');
    return 2; // does not get returned  
  }

You give this as the second argument of your call to userProfile.find. When the find is completed, the function is called returning 2, but by this time it is too late and you have already console.logged x which was undefined at the time.

Hippocrates
  • 2,510
  • 1
  • 19
  • 35