1

How does Javascript create the callback functions for asynchronous loops? Does it recreate the function every time or just create it once and use the same function definition on every iteration it needs? I am using AngularJS for a multifile file uploader using the following project. And there is this function, that deals with the progress bar called progress. Here is the basic upload. There is nothing fancy happening. Just default callback functions:

$scope.uploads = {};

for (var i = 0; i < $files.length; i++) {
    $scope.upload = $upload.upload({
        url: '/storage/upload',
        file: $files[i],
        data: data
    }).progress(function(e) {
        $scope.uploads[i] = e.loaded / e.total;
    }).success(function(data, status, headers, config) {
        $scope.reload();
    });
}

I also have another function that, for now just does console.log($scope.uploads). For testing purposes I am trying to upload four files. Here is what I get from the log:

Object 4: 0.4744183257889485

Object 4: 1

Object 4: 0.4563747067454433

etc. It basically only updates one value of $scope.uploads, the 4th value and after thinking for some time I realized that Javascript has the same scoping as PHP - If a variable is defined in the scope, one can access it outside the scope. And since the last file's index is 3, it adds the last one and ends the loop, but the variable still exists in the class and therefore the progress function just keeps updating the last i, instead of the ones that it was provided with at first.

How can I assign the iteration variables to these functions, so even after the loop is ended, the function still uses the value that was first assigned during the 'initialization' of the object?

Gasim
  • 7,615
  • 14
  • 64
  • 131
  • 1
    Different anonymous function every time, but same `i`. `angular.forEach` can solve this problem too since it creates a scope for each iteration with each scope having it's own `i`. – Kevin B Sep 04 '14 at 20:32
  • Thank you for the link and reference to `angular.forEach`. I now know how to handle this problem in the future :) – Gasim Sep 04 '14 at 20:42

0 Answers0