要重复调用函数,直到它使用promise-Angularjs满足条件

时间:2014-10-08 15:07:57

标签: angularjs promise angular-promise

我想在服务器上连续发布图像,我这样做是通过将它放在图像长度的循环中。我想使用promises在上一次图像上传成功后再次调用该函数。 以下是我正在使用的代码

$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");
            }
        })
//  });
}

我搜索了使用promises但没有成功的方法。我希望在每个调用成功时执行此操作,直到条件满足为止

1 个答案:

答案 0 :(得分:1)

使用promises创建受控无限循环可能有点棘手。 我在这里为您构建了一个基本功能,但您需要修改它以适用于您的

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