异步Javascript变量覆盖 [英] Asynchronous Javascript Variable Overwrite

查看:57
本文介绍了异步Javascript变量覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码有一个问题,即在调用异步函数时,变量会被覆盖。怎么修好?

The code has an issue that the variable gets over written when the asynchronous function is called. How can it be fixed?

代码:

for (x in files) {

 asynchronousFunction(var1, var2, function(){
      console.log(x.someVaraible);
  }); 

}

现在的问题是异步函数中的回调函数被称为x.files变量已被更新为json数组文件中的下一个变量。我希望变量应该包含以前的值。

Now the issue is that when the callback function in the asynchronousFunction is called the x.files variable has been updated to the next varaible in the json array files. I want that the variable should contain the previous value.

回调函数中的变量数量不能更改,因此无法在回调函数中发送变量名称函数。

The number of variables in the callback function can not be changes, so variable name can not be sent in the call back function.

推荐答案

在javascript中使用'local'变量的问题是你的变量实际上有函数作用域,而不是块作用域 - 比如java和c#等已经

The problem wtih using 'local' variables in javascript is that your variables actually have function scope, rather than block scope - like java and c# etc has

解决这个问题的一种方法是使用 let 哪个有块范围,但是目前只有firefox支持这个。

One way to get around this is using let which has block scope, but only firefox supports this currently.

所以这段代码只适用于firefox:

So this code would work in firefox only :

for (var x in files) {
  // This variable has BLOCK scope
  let file = files[x];
  asynchronousFunction(var1, var2, function(){
     console.log(file.someVaraible);
  }); 
}

对于其他浏览器,替代方法是使用闭包

For other browsers, the alternative is to use closures

for (var x in files) {
  var file = files[x];
  asynchronousFunction(var1, var2, (function(file){
      return function() {
                console.log(file.someVaraible);
             };
  })(file); 
}

另一种方法是使用map / forEach,假设文件的数据类型是数组。

Another way you could do this is using map/forEach, assuming that the datatype of files is an array.

files.forEach(function(file) {
     asynchronousFunction(var1, var2, function(){
                console.log(file.someVaraible);
             });
});

如果它不是数组,那么你总是可以使用这种技术

If it's not an array, then you can always use this technique

 [].forEach.call(files, function(file) {
     asynchronousFunction(var1, var2, function(){
                console.log(file.someVaraible);
             });
});

更全面的写作方式当然是

The fuller way of writing this is of course

Array.prototype.forEach.call(files, function(file) {
     // As before

但我觉得 []。forEach 眼睛更好

这篇关于异步Javascript变量覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆