我是Node.js平台的新手,我正在尝试学习尽可能多的东西。在使用回调后,一件事确实使我感到困惑:
所以,我有这个功能:
function registerUser(body, res, UserModel){
var userJSON = {
email : body.email,
password : body.password,
accessToken : null
};
var user = null;
var userAlreadyExists = false;
UserModel.find({}).select('email').exec(function(err, results){
if(err){
console.log('Database error : ' + err);
// send the appropriate response
}else{
for(var index in results){
if(results[index].email == userJSON.email){
userAlreadyExists = true;
break;
}
}
if(userAlreadyExists){
// send the appropriate response
}else{
newAccessToken(UserModel, function(error, token){
if(error != null){
// handle the error
}else{
userJSON.accessToken = token;
user = new UserModel(userJSON);
user.save(function(err){
if(err){
// .. handle the error
}else{
// .. handle the registration
}
});}});}}});}
然后接受回调的函数:
function newAccessToken(UserModel, callback){
UserModel.find({}).select('email accessToken').exec(function(err, results){
if(err){
callback(err, null);
}else{
// .... bunch of logic for generating the token
callback(null, token);
}
});
}
我预计回调不工作(也许抛出一个错误),因为二者user
并userJSON
没有在它的上下文定义(当然,这是不完全正确的,但因为它是执行异步- 。过了一会儿- ,我希望回调失去对那些在registerUser
函数中本地定义的变量的引用)。取而代之的是,该示例可以完美地工作,回调函数使用在registerUser
函数中定义的两个变量来保持其引用。有人可以向我解释异步回调和引用如何工作,以及示例为何工作吗?
嗨,您“回溯到”的函数在您要访问的变量的范围内,因此访问它们非常有用。
这不是nodejs的事情,常规JS的工作方式相同。
区别
1)将无法访问名为“ foo”的变量
function finishfunction() {
console.log(foo); /* undefined */
}
function functionwithcallback(callback) {
callback();
}
function doStuff() {
var foo = "bar";
functionwithcallback(finishfunction);
}
doStuff();
2)像您一样,可以访问“ foo”。
function functionwithcallback(callback) {
callback();
}
function doStuff() {
var foo = "bar";
functionwithcallback(function() {
console.log(foo) /* all fine */
});
}
doStuff();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句