0

I'm feeling stupid but i dont find what is the problem here

var images = [];

angular.forEach($scope.flow.images.files, function (flowFile, i) {
    var fileReader = new FileReader();
    fileReader.onload = function (event) {
        var uri = event.target.result;
        images.push(uri);
        console.log(images.length); // First iteration length = 1, second iteration length = 2 
    };

    console.log(images.length); // Always shows 0
    fileReader.readAsDataURL(flowFile.file);

});

Can anyone help me understand?

Cristhian Boujon
  • 4,060
  • 13
  • 51
  • 90

1 Answers1

0

It's to do with the asynchronous nature of JavaScript. The log of images.length occurs before the fileReader.onload function is fired despite it sequentially occurring after, hence the discrepancies in the content of the images array.

To circumvent this behaviour and avoid callback hell, take a look at this tutorial on Promises in JavaScript.

Ryan Brodie
  • 6,554
  • 8
  • 40
  • 57