I have the following code which runs in a loop:
var index = fileNames[x].lastIndexOf("/") + 1;
var currentImageName = fileNames[x].substr(index);
if (currentImageName.indexOf(".jpg") != -1) {
reader.getFileAsBlob(fileNames[x])
.done(function(blob) {
picturesFilePathArray.push({
fileName: currentImageName,
fileURL: blobURL(blob)
});
refreshKMZList();
});
}
The problem I am having is that I am trying to save an object with 2 properties into an array. This object should have the identifier and the result. (fileName and fileURL respectively). But since this function is asynchronous (executed through a promise). By the time the "getFileAsBlob" finishes, currentImageName has already been updated ultimately ending in many of my objects having the same identifier (the last one processed before it finished).
This might be a really easy problem, but I am very new to javascript and haven't yet found anything about it.
I thought that the solution might be in passing the variable to the "done" function, but I think this function is the one being returned by the method and is already set. (I dont know how it looks)
Edit:
The code is just inside a normal loop
for (x = 0; x<fileNames.length; x++)
The solution to this problem is always the same: Use a closure.
But since you are using a promise based library, you have a nicer option. Use promises. (Internally this is based on closures as well, of course. It's just a much nicer abstraction.)
Now you can do this, where
refreshKMZList()
is called once per file:or even this, where
refreshKMZList()
is called only once per overall:Read up on promises, they are worth being understood.
So create a function so the variable can not be changed
and call it
or you can do something like
MDN Closure