有人能帮我解决一些Angular承诺问题吗? 我有以下函数,应该接受一个文件对象数组,遍历每个对象并上传。 每次迭代期间,会将Promise对象推到一个promises
数组中。 在我的upload
函数中,我有一个cycle
函数,附有一个.then()
,它不应在所有承诺对象都已解析之前被调用。 我认为我的代码看起来正确,但是它无法正常工作。 图像上传成功,但是cycle(files).then()
立即被调用,而不是等到promises
数组解析后再执行。
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.promise
推入promises
数组,然后在我的.success()
回调中解析deferred
,但这并没有起作用,我只需将不带有.success()
回调的Upload.upload()
函数推入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);
})
};