简体   繁体   English

Node.js回调功能

[英]Node.js callback functionality

I'm new to the Node.js platform and I'm trying to learn as much as I can. 我是Node.js平台的新手,我正尽力学习。 After playing with callbacks one thing really confuses me: 玩回调后,有一件事让我很困惑:

So, I have this function : 所以,我有这个功能:

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

And then the function which accepts the callback: 然后是接受回调的函数:

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

    });
}

I would expect the callback to not work(maybe throw an error) since both user and userJSON are not defined in it's context.(well, that's not exactly true, but since it is executed async - after a while - , I would expect the callback to lose it's references to those variables, which were defined locally in the registerUser function). 我希望回调不起作用(可能会抛出一个错误),因为useruserJSON都没有在它的上下文中定义。(好吧,这不完全正确,但因为它执行异步 - 一段时间后 - ,我希望回调失去它对那些在registerUser函数中本地定义的变量的引用。 Instead this example works perfectly, the callback function keeps it's references with those two variables defined in the registerUser function. 相反,这个例子工作得很好,回调函数使用registerUser函数中定义的那两个变量来保持它的引用。 Could somebody explain me how the async callback and the references work and why does the example work? 有人可以解释一下异步回调和引用是如何工作的,为什么这个例子有效?

Instead of callbacks, those are called closures, and in JavaScript the scope treatment is special. 这些被称为闭包而不是回调,而在JavaScript中,范围处理是特殊的。 Check this document: 查看此文档:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

H i, the function you 'calllback to' is within the scope of the variables you are trying to access, so all good to go for accessing them. H I,你的函数“calllback为”是您试图访问的变量的范围之内 ,所以都好去访问它们。

This is not a nodejs thing, regular JS works the same way . 这不是nodejs的事情,常规的JS以同样的方式工作。

The difference 区别

1) Will not be able to access a var called 'foo' 1)将无法访问名为'foo'的var

function finishfunction() {
  console.log(foo); /*  undefined */
}

   function functionwithcallback(callback) {
       callback();
  }

  function doStuff() {

     var foo = "bar";

    functionwithcallback(finishfunction);

 }

 doStuff();

2) like yours, access to 'foo' is fine. 2)和你一样,访问'foo'很好。

   function functionwithcallback(callback) {
       callback();
  }

  function doStuff() {

     var foo = "bar";

    functionwithcallback(function() {

    console.log(foo) /* all fine */

    });

 }

 doStuff();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM