blueimp/JavaScript-Load-Image

Please a solution for upload multiple

yourchoice opened this issue · 1 comments

I have this code:

I read and this #16

$('#up-inputfile').change(function(e) {
  var files = e.target.files,
    len = files.length;
  for(var i = 0; i < len; i++) {
    console.log('index i: ', i);
    loadImage(files[i],
      function (img) {
        console.log('loadImage ['+i+']');	
      },
      { meta: true }
    );
  }
  console.log('last i:', i);
});

If I upload 2 files, I get in logs:
index i: 0
index i: 1
last i: 2
loadImage [2]

Seems that loadImage comes after the for() block ....

Hi @yourchoice,

the behavior you're seeing is due to how JavaScript closures work:
loadImage() is an asynchronous function and will execute the callback after your loop has finished. At that point, your counter variable has the value of files.length and will be logged as such.

If you'd like a deeper introduction to the topic of closures, I recommend this book:
https://github.com/getify/You-Dont-Know-JS/tree/2nd-ed/scope-closures

I also recommend the whole book series for anyone wanting to get a better understanding of JavaScript, it's one of the best out there:
https://github.com/getify/You-Dont-Know-JS/

Since your post is not an issue with this library, I'll close this.