我已經對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();
});
});
這裏打印路徑的值時,在函數內部它給分配的新值,但打印功能外,第二次時,它並沒有給新的價值。
如何解決此問題。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures –