Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a variable to an asynchronous function (promise) in javascript

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++)
like image 756
Pochi Avatar asked Jan 15 '14 14:01

Pochi


1 Answers

So create a function so the variable can not be changed

function getFile (filmName, imageName) {
    reader.getFileAsBlob(fileName)
    .done(function(blob) {
        picturesFilePathArray.push({
           fileName: imageName,
           fileURL: blobURL(blob)
        });
       refreshKMZList();
    });
}

and call it

if (currentImageName.indexOf(".jpg") != -1) {
    getFile (fileNames[x], currentImageName);
}

or you can do something like

if (currentImageName.indexOf(".jpg") != -1) {
    (function (fileName, imageName) { 
    reader.getFileAsBlob(fileName)
        .done(function(blob) {
            picturesFilePathArray.push({
               fileName: imageName,
               fileURL: blobURL(blob)
            });
           refreshKMZList();
        });
    })(fileNames[x], currentImageName);
}

MDN Closure

like image 188
epascarello Avatar answered Oct 02 '22 19:10

epascarello