回调的闭包问题
Closure issue with callback
我有一个回调关闭问题。
每次调用这个函数,我得到tmp
= 1。我在回调中设置它。
为什么会发生?我该如何解决它呢?
var tmp = 1;
var getConnection = function() {
console.log(tmp);
MongoClient.connect(url, function(err, db) {
tmp = 2;
});
};
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。
为了回答你的问题,我认为缺少一些数据。
我猜你在某种循环中调用getConnection()
函数,例如
for (var i = 0; i < l; ++i) {
getConnection(i);
}
在这种情况下,串行代码(即循环和console.log(tmp)
)将在所有回调之前执行,在您的情况下:
function(err, db) {
tmp = 2; // set tmp to 2
}
'1'将始终显示,因为只有在写入控制台后,该值才会更新为'2'。
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
作为全局变量并不是一个好主意,它可能会被其他变量污染,并可能导致许多问题
相关文章:
- 作用域问题-此函数是否形成闭包-JavaScript
- JavaScript + mocha:可能是在 for 循环中声明函数的闭包问题
- grunt闭包工具配置多个目标的问题
- Javascript;promise中存在Q-闭包问题
- 对象的闭包编译器问题
- Node.js:异步代码 + js 闭包的问题
- 我在循环中遇到闭包问题,但我仍然使用单独的功能
- 创建带有回调的动态 JSON 数组(内部闭包问题)
- javascript中奇怪的闭包问题
- 简单的Javascript闭包问题
- 如何解决angularjs中的闭包问题
- 数组中jQuery元素的常见JavaScript闭包问题
- 试图理解js中的闭包问题
- 如何通过闭包问题来增加全局变量
- 循环(事件)中的闭包问题
- 不能将事件传递给addEventListener:闭包问题
- 可能是另一个Javascript闭包问题
- 闭包的问题.任何提示
- JavaScript闭包和作用域问题
- 闭包和“this”的问题关键字