2016-11-24 19 views
0

Ich verwende eine ForEach-Schleife, um Bild (API-Aufruf) hochladen, ich möchte die Schleife warten, bis die Antwort des vorherigen Index ankommt. Hier ist mein Code:Führen Sie einen API-Aufruf auf einmal in Foreach-Schleife

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

Antwort

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 
} 

Dann rufen Sie die Funktion und das Versprechen

PostData(myArray).then(function(success){ 
    // successcallback 
    }, function(error){ 
    // errorcallback 
}); 

Hinweis zu lösen, die ich habe nicht wirklich den obigen Code implementiert, aber das sollte man mit einer möglichen bieten Ansatz.

+0

Upload.upload (ich benutze ng-Datei-Upload-Modul) wird für API-Aufruf verwendet, also möchte ich die Schleife bis zur Antwort für den vorherigen Anruf unterbrechen. Ich habe den obigen Code ausprobiert, aber immer noch das gleiche Problem. –

+0

Ok, siehe meine aktualisierte Antwort – sjokkogutten

Verwandte Themen