0

预期输出:“x is 2” 实际输出:“x is undefined”

应用程序.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  
    });
}
4

2 回答 2

3

使用回调函数:

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);
    });
};
于 2013-09-13T13:41:54.853 回答
1

userProfile.find 是异步的,这意味着它会被启动,但直到您的 console.log 被触发后才会返回 2。你的回调是这个函数:

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

您将此作为调用的第二个参数userProfile.find。查找完成后,调用该函数返回 2,但此时为时已晚,您已经 console.logged x 那时未定义。

于 2013-09-13T13:43:12.140 回答