簡體   English   中英

Node.js回調功能

[英]Node.js callback functionality

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

    });
}

我希望回調不起作用(可能會拋出一個錯誤),因為useruserJSON都沒有在它的上下文中定義。(好吧,這不完全正確,但因為它執行異步 - 一段時間后 - ,我希望回調失去它對那些在registerUser函數中本地定義的變量的引用。 相反,這個例子工作得很好,回調函數使用registerUser函數中定義的那兩個變量來保持它的引用。 有人可以解釋一下異步回調和引用是如何工作的,為什么這個例子有效?

這些被稱為閉包而不是回調,而在JavaScript中,范圍處理是特殊的。 查看此文檔:

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

H I,你的函數“calllback為”是您試圖訪問的變量的范圍之內 ,所以都好去訪問它們。

這不是nodejs的事情,常規的JS以同樣的方式工作。

區別

1)將無法訪問名為'foo'的var

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM