2015-09-21 170 views
6

任何人都可以幫助我一些角度的承諾?我有以下函數應該在文件對象數組中進行迭代,然後上傳每個文件對象。在每次迭代期間,承諾對象被推送到一個數組promises。在我的upload函數中,我有一個cycle函數,附帶一個.then()函數,直到所有promise對象都解析完畢才能調用函數。我認爲我的代碼看起來是正確的,但它不正確。圖像上傳,但cycle(files).then()立即被調用,而不是一旦promises陣列解決。AngularJS承諾數組

function upload(files) { 
    var uploadCount = files.length; 
    function cycle(files) { 
     var promises = []; 
     for (var i = 0; i < files.length; i++) { 
      var deferred = $q.defer(); 
      promises.push(deferred); 
      var file = files[i]; 
      Upload.upload({ 
       url: '/photos.json', 
       file: file 
      }).success(function(){ 
       $scope.progressCurrentCount += 1; 
       deferred.resolve(); 
      }); 
     }; 
     return $q.all(promises); 
    }; 

    cycle(files).then(function(result) { 
     if(uploadCount > 1) { 
      $scope.lastAction = 'uploaded ' + uploadCount + ' photos'; 
     } else { 
      $scope.lastAction = 'uploaded ' + uploadCount + ' photo'; 
     } 
     $scope.showSuccessModal = true; 
     $scope.uploading = false; 
     $scope.failedUploads = []; 
     $scope.newPhotos = { 
      token: $scope.token, 
      files: undefined 
     }; 
     photoUploadBtn.removeClass('disabled'); 
    }) 
}; 

最後的工作代碼*

,而不是設置var deferred = $q.defer();deferred.promisepromises數組,然後在我的.success()的回調,這是行不通的解決deferred,我只是把我的Upload.upload()功能,無需將.success()回調爲promises,然後將其傳遞給$q.all(),這樣做完全解除。

function upload(files) { 
    var uploadCount = files.length; 
    function cycle(files) { 
     var promises = []; 
     for (var i = 0; i < files.length; i++) { 
      var file = files[i]; 
      var promise = Upload.upload({ 
       url: '/photos.json', 
       file: file 
      }); 
      promises.push(promise); 
     }; 
     return $q.all(promises); 
    }; 

    cycle(files).then(function(result) { 
     if(uploadCount > 1) { 
      $scope.lastAction = 'uploaded ' + uploadCount + ' photos'; 
     } else { 
      $scope.lastAction = 'uploaded ' + uploadCount + ' photo'; 
     }; 
     $scope.showSuccessModal = true; 
     $scope.uploading = false; 
     $scope.failedUploads = []; 
     $scope.newPhotos = { 
      token: $scope.token, 
      files: undefined 
     }; 
     photoUploadBtn.removeClass('disabled'); 
     getPhotos(q); 
    }) 
}; 

回答

11

必須按一個承諾,而不是推遲,到promises陣列:

promises.push(deferred.promise); 

它幫助,如果你仔細想想這樣的:

  • 的承諾是讀 - 僅限於您想要返回給消費者的對象
  • 延遲是該只讀承諾的修飾符,並且您想保留自己
+0

謝謝,那是我需要的大部分解決方案!我也遇到了[這篇文章](https://www.jonathanfielding.com/combining-promises-angular/),這讓我意識到我應該以不同的方式處理事情。我將把我的最終代碼放在上面的文章中。 – ACIDSTEALTH