title: Passing a variable to an asynchronous function (promise) in javascript
body: <p>I have the following code which <strong>runs in a loop</strong>:</p>
  
  <pre><code>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();
      });
  }
  </code></pre>
  
  <p>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).</p>
  
  <p>This might be a really easy problem, but I am very new to javascript and haven't yet found anything about it.</p>
  
  <p>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)</p>
  
  <p>Edit: </p>
  
  <p>The code is just inside a normal loop</p>
  
  <pre><code>for (x = 0; x&lt;fileNames.length; x++)
  </code></pre>