Sangram Singh
Sangram Singh

Reputation: 7191

Error in Returning Value of Function

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

Upvotes: 0

Views: 56

Answers (2)

Hippocrates
Hippocrates

Reputation: 2540

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.

Upvotes: 1

mguimard
mguimard

Reputation: 1901

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

Upvotes: 3

Related Questions