Saturday 9 June 2018
Asynchronous Javascript Variable Overwrite
Answer
Answer
The code has an issue that the variable gets over written when the asynchronous function is called. How can it be fixed?
Code:
for (x in files) {
asynchronousFunction(var1, var2, function(){
console.log(x.someVaraible);
});
}
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.
Answer
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
One way to get around this is using let
which has block scope, but only firefox supports this currently.
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);
}
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
But I feel [].forEach
is nicer on the eyes
php - file_get_contents shows unexpected output while reading a file
I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...
-
I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like th...
-
I got an error in my Java program. I think this happens because of the constructor is not intialized properly. My Base class Program public ...
-
I would like to use enhanced REP MOVSB (ERMSB) to get a high bandwidth for a custom memcpy . ERMSB was introduced with the Ivy Bridge micro...
No comments:
Post a Comment