【发布时间】:2016-03-21 12:09:25
【问题描述】:
我对我们的 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();
});
});
在这里,当在函数内部打印 pass 的值时,它会给出分配的新值,但在函数外部第二次打印时,它不会给出新值。
如何解决这个问题。
【问题讨论】:
标签: node.js