node.js:asynchronouscallback值

我很困惑。 我很想学习如何传递我在asynchronous函数中获得的值。

我有一个基本的身份validationfunction的模块。 在login时,我要求用户模型search具有给定用户名的用户。

login: function(req){ var username = req.body.username, password = req.body.password; user.find(username); } 

然后,用户模型继续,并做到这一点。

 exports.find = function(username){ console.log(User.find({username: username}, function(error, users){ // I get nice results here. But how can I pass them back. })); } 

但是,我怎么能通过该用户对象回loginfunction?

您需要将callback函数传递给该方法。 Node.js需要一个非常callback驱动的编程风格。

例如:

 // in your module exports.find = function(username, callback){ User.find({username: username}, function(error, users){ callback(error, users); }); } // elsewhere... assume you've required the module above as module module.find(req.params.username, function(err, username) { console.log(username); }); 

所以你不要返回值; 你传递的函数,然后收到的价值(冲洗,重复)

用户类的login方法将如下所示:

 login: function(req, callback){ var username = req.body.username, password = req.body.password; user.find(username, function(err, user) { // do something to check the password and log the user in var success = true; // just as an example to demonstrate the next line callback(success); // the request continues }; } 

你不能将它传递回去 (因为asynchronous函数和login函数在完成时已经返回)。 但是你可以把它传递给另一个函数。