1

I want to post images on server continuously and i am doing this by putting it in a loop of images length.I want to call the function again on the success of previous image upload using promises. Below is the code i am using

$scope.questionimageuploadfun = function(surveyid, questionid, type, questions) {
    angular.forEach(questions, function(value, key) {
        $scope.upload = $upload.upload({
            url: 'questions/' + questionid + '/options/' + value.id,
            file: value.file,
            fileFormDataName: 'myfile',
        }).progress(function(evt) {
            console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
        }).success(function(data, status, headers, config) {
            // file is uploaded successfully
            if (!data.error && type == "new") {
                toaster.pop('success', "Question", "Question added succesfully");
            }
        })
//  });
}

I searched for the way to use promises but no success.I want to do this on success of every call till the condition gets satisfies

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Namdeo Karande
  • 403
  • 1
  • 3
  • 19

1 Answers1

1

To create a controlled infinite loop with promises can be a bit tricky. I structured a basic function here for you, but you need to modify it to work to your

$scope.questionImageUploadFun = function(surveyid,questionid,type,questions){

    var defer = $q.defer(); // the deferred object, a promise of work to be done

    $http.get('someUrl', parameters).then(function(response){
        // do something with success response
        defer.resolve(response);
    }, function(reasonForFail){
        // do something with failure response
        defer.reject(reasonForFail);
    });

    return defer.promise; // return the promise
};

// define success function
var onSuccess = function(response){
    // declare local parameters here
    // call function again
    $scope.questionImageUploadFun().then(onSuccess); // success function should call itself again on the next success
};

var onFailure = function(reason){
    // do something else?
};

var surveyId = 1;
var questionId = 1;
var type = 1;
var question = 1;

// call the function, since it returns a promise, you can tag a then() on the end of it, and run the success function.
$scope.questionImageUploadFun(surveyid,questionid,type,questions).then(onSuccess);
SoluableNonagon
  • 11,541
  • 11
  • 53
  • 98