2016-03-21 28 views
0

我已經對node.js的異步屬性和回調的功能做了大量的閱讀。Node.js變量作用域之外

但是,我不明白,如果我定義一個函數,並更改該函數內的變量的值,那麼爲什麼它不在函數外部可用。

讓我通過一個例子來展示我一直在努力的代碼。

var findRecords = function(db, callback) { 

var cursor =db.collection('meta').find({"title":"The Incredible Hulk: Return of the Beast [VHS]"}, {"asin":1,_id:0}).limit(1); 
pass=""; 
cursor.each(function(err, doc) { 
     assert.equal(err, null); 
     if (doc != null) { 
      var arr = JSON.stringify(doc).split(':'); 
      key = arr[1]; 
      key = key.replace(/^"(.*)"}$/, '$1'); 
      pass =key; 
      console.log(pass); //Gives correct output 
     } 

    }); 

    console.log(pass) //Does not give the correct output 

}; 



MongoClient.connect(url, function(err, db) { 
    assert.equal(null, err); 

    findRecords(db, function() { 
     db.close(); 
    }); 
}); 

這裏打印路徑的值時,在函數內部它給分配的新值,但打印功能外,第二次時,它並沒有給新的價值。

如何解決此問題。

+0

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

回答

0

而不是通過=「」
首先聲明它並嘗試這個var pass =「」;

+0

這是行不通的。 – Arqam

1
let pass = 'test'; 

[1, 2, 3].map(function(value) { 
    let pass = value; 
    // local scope: 1, 2, 3 
    console.log(pass); 
}); 

console.log(pass); // => test 

// ------------------------------ 

let pass = 'test'; 

[1, 2, 3].map(function(value) { 
    pass = value; 
    // local scope: 1, 2, 3 
    console.log(pass); 
}); 

// the last value from the iteration 
console.log(pass); // => 3 

// ------------------------------ 

// we omit the initial definition 

[1, 2, 3].map(function(value) { 
    // note the usage of var 
    var pass = value; 
    // local scope: 1, 2, 3 
    console.log(pass); 
}); 

// the variable will exist because `var` 
console.log(pass); // => 3 

// ------------------------------ 

// we omit the initial definition 

[1, 2, 3].map(function(value) { 
    // note the usage of var 
    let pass = value; 
    // local scope: 1, 2, 3 
    console.log(pass); 
}); 

// the variable will not exist because using let 
console.log(pass); // => undefined 
1

嘗試使用:

var pass=""; 
var that = this; 
cursor.forEach(function(err, doc) { 
     assert.equal(err, null); 
     if (doc != null) { 
      var arr = JSON.stringify(doc).split(':'); 
      key = arr[1]; 
      key = key.replace(/^"(.*)"}$/, '$1'); 
      pass =key; 
      console.log(pass); //Gives correct output 
     } 

    }, that); 
console.log(pass);