我正在使用forEach循环来上传图像(API调用),我希望循环等到Previous index的响应到来。 这是我的代码:
var uploadCount = 0;
angular.forEach($scope.selectedLayouts, function (layout, pIndex) {
angular.forEach(layout.data, function (data, cIndex) {
if(data.imageIsChanged && $scope.uploadImgCount !== 0) {
Upload.upload({
url: window.apiUrl + 'image_upload',
data: {
'image' : data[$scope.indexes.image]
}
}).then(function(resp) {
uploadCount++;
data[$scope.indexes.image] = resp.data.path;
if($scope.uploadImgCount === uploadCount) {
$scope.uploadImgCount = uploadCount = 0;
}
}, function(error) {
uploadCount++;
toastr.error(error);
});
}
});
});
答案 0 :(得分:0)
function PostData(myArray) {
var i = 0; // Array index counter
var deferred = $q.deferred(); // Create promise using $q.deferred();
var promises = [] // An array of your request results as promises
function nextRequest() { // make the next request in you array
var request_promise = Upload.upload({
var postData = myArray[i];
// the rest of your code ...
}) // assumes Upload.upload returns a promise
.then( function (data){
// OnSuccess callback
promises.push(data); // save result in array
i++; // increment index
// Continue if there are more items.
if (currentRequest < someArray.length){
nextRequest();
}
else { // Resolve the promise when finished
deferred.resolve(results);
}
}, function(error){
// errorcallback
}
)};
return deferred.promise; // return a promise for the completed requests
}
然后调用该函数并解决承诺
PostData(myArray).then(function(success){
// successcallback
}, function(error){
// errorcallback
});
请注意,我实际上没有实现上面的代码,但这应该为您提供一种可能的方法。