我的回调问题是关闭。
每次调用此函数时,我都会得到tmp
等于1。
并且我在回调中设置它..
为什么会这样?我该如何解决呢?
var tmp = 1;
var getConnection = function() {
console.log(tmp);
MongoClient.connect(url, function(err, db) {
tmp = 2;
});
};
答案 0 :(得分:0)
var tmp = 1; // set tmp to 1
var getConnection = function() {
console.log(tmp); // log current value of tmp
MongoClient.connect(url, function(err, db) {
tmp = 2; // set tmp to 2
});
};
我没有看到getConnection()
被调用,但我们假设您在声明后立即调用它。
getConnection()
中发生的情况是1)记录tmp
的当前值,然后2)尝试连接到Mongo,然后3)将tmp
的值设置为2。
答案 1 :(得分:0)
我认为缺少一些数据才能回答你的问题。
我的猜测是你在某种循环中调用getConnection()
函数,例如
for (var i = 0; i < l; ++i) {
getConnection(i);
}
在这种情况下,串行代码(即循环和console.log(tmp)
)将在所有回调之前执行,在您的情况下:
function(err, db) {
tmp = 2; // set tmp to 2
}
'1'将始终显示,因为在将写入控制台后,该值将仅更新为<2> 。
答案 2 :(得分:0)
MongoClient.connect
是异步操作,因此,如果您想使用tmp
的更新值,您应该执行以下操作:
var tmp = 1; // set tmp to 1
var getConnection = function(callback) {
var ctx = this; //or whatewever you want the context to be
console.log(tmp); // log current value of tmp
MongoClient.connect(url, function(err, db) {
tmp = 2; // set tmp to 2
callback.call(ctx, tmp); //you have to choose the context
});
};
getConnection(function(tmp){
//do some magic with tmp
})
顺便说一下,将tmp
作为全局变量并不是一个好主意,它可能会被其他人污染并导致很多问题