2016-11-24 205 views
0

我正在使用forEach循环上传图像(API调用),我希望循环等待直到前一个索引的响应到达。 这里是我的代码:在foreach循环中一次执行一个API调用

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
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 
}); 

请注意,我并没有实际执行上面的代码,但是这应该为你提供一个可能的做法。

+0

Upload.upload(我正在使用ng-file-upload模块)用于API调用,所以我想打破这个循环直到前一个调用的响应。我尝试了上面的代码,但仍然遇到了同样的问题。 –

+0

好的,看我更新的答案 – sjokkogutten