2

I have an array of functions, where each function returns promise from ajax call.

var promises = [];
if (form.$valid) { 
  Object.keys($scope.Model.Data.FormFiles).forEach(function (key) {
    var file = $scope.Model.Data.FormFiles[key];

    function uploadFile(){
        var deferred = $q.defer();
        var upload = Upload.upload({
            url: "/api/ir/funnelApi/UploadFile",
            data: { file: file }
        });

        upload.then(function (response) {                           
                // do something
                deferred.resolve(response.statusText);
            }, function (error) {
                deferred.reject(error.data);
            }, function (evt) {

        });             
        return deferred.promise;
    }       

    promises.push(uploadFile);
  });   
}

What i am trying to do is, if all the file has been uploaded successfully then do something.

$q.all(promises).then(function (responses) {                    
   // do something
}, function (errors) {
   // if any of the file upload fails, it should come here  
});

But the problem is the ajax are never fired and the $q.all always moves to success with the function array.

What's the wrong i am doing??

Mahbubur Rahman
  • 4,961
  • 2
  • 39
  • 46

1 Answers1

5

You are pushing references of the function to array....not invoking the function and pushing the returned promise

Try changing:

promises.push(uploadFile);

to

promises.push(uploadFile());

Creating a new promise using $q.defer(); is also an antipattern when Upload.upload() already returns a promise and you could simply return that instead

Community
  • 1
  • 1
charlietfl
  • 170,828
  • 13
  • 121
  • 150