使用promise Angularjs重复调用函数本身,直到满足条件

使用promise Angularjs重复调用函数本身,直到满足条件,angularjs,promise,angular-promise,Angularjs,Promise,Angular Promise,我想在服务器上连续发布图像,我把它放在一个图像长度的循环中。我想在使用promises成功上传之前的图像时再次调用该函数。 下面是我正在使用的代码 $scope.questionimageuploadfun = function(surveyid, questionid, type, questions) { angular.forEach(questions, function(value, key) { $scope.upload = $upload.upload({

我想在服务器上连续发布图像,我把它放在一个图像长度的循环中。我想在使用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");
            }
        })
//  });
}

我搜索了使用承诺的方法,但没有成功。我希望在每次调用成功时都这样做,直到条件满足为止。创建一个带有承诺的受控无限循环可能有点棘手。 我在这里为您构建了一个基本函数,但您需要修改它以适应您的需要

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

这可能有点棘手,但你所做的并不是这样。也请考虑阅读延迟反模式,什么是“条件”?