'Execute a function after angular foreach

I'm trying to do that after the foreach angle, perform a function to save on server images on the bench.

But problem is that the function is executed before finishing the foreach, me returning an empty array.

FUNCTIONS:

$scope.processFiles = function(images){
    if(!$rootScope.client.media) $rootScope.client.media = [];

    angular.forEach(images, function(flowFile, i){
        var fileReader = new FileReader();

        fileReader.onload = function (event) {
            var uri = event.target.result;

            $scope.image = {
                filename: uri
            };

            $rootScope.client.media.push($scope.image);
        };

        fileReader.readAsDataURL(flowFile.file);
        //$scope.saveFiles();
    });
};

$scope.saveFiles = function() {
    $rootScope.client.put({client: $rootScope.client.client})
    .then(function(res){
        $rootScope.client = res;
        toast.msgToast('Arquivos de imagens atualizados com sucesso.');
    });
};

HTML:

<md-card>
    <md-toolbar ng-show="!selectedmedia.length" class="md-table-toolbar md-default">
        <div class="md-toolbar-tools">
            <h2 class="md-title">imagens</h2>
            <div flex></div>
            <md-button class="md-icon-button" aria-label="Upload imagem" flow-btn>
                <md-icon>add</md-icon>
                <md-tooltip>Upload imagem</md-tooltip>
            </md-button>
        </div>
    </md-toolbar>


Solution 1:[1]

In your case, you are using two asynchronous functions:

  • angular.forEach
  • fileReader.onload

In order to find out when they are carried out best to use promise.

Example on jsfiddle.

angular.module('ExampleApp', [])
  .controller('ExampleController', function($timeout, $q) {
    var vm = this;
    vm.doneSave = false;
    vm.media = [];
    vm.startSave = function() {
      vm.media = [];
      vm.doneSave = false;
      var images = [1, 2, 3, 4, 5];
      var promises = [];
      angular.forEach(images, function(image) {
        var defer = $q.defer();
        console.log('forEach', image);
        //simulate fileReader.onload
        $timeout(function() {
          vm.media.push("saved: " + image);
          console.log('saved', image);
          // we done here. Resolve the promise
          defer.resolve(image);
        }, image * 1000);
        promises.push(defer.promise);
      });          
      $q.all(promises).then(function() {// executed, then all promises resolved
        vm.onSaved();
      }).catch(console.error);
    }
    vm.onSaved = function() {
      vm.doneSave = true;
      console.log('on saved', vm.media);
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="ExampleController as vm">
    <form name="myForm">
      <div ng-show="vm.doneSave">
        Saving done!
      </div>
      <div ng-show="!vm.doneSave">
        Click to save!
      </div>
      <button ng-click="vm.startSave()">
        Save
      </button>
    </form>
  </div>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stepan Kasyanenko