链接承诺并在角度应用程序中使用for循环延迟

时间:2013-11-22 11:44:26

标签: javascript angularjs service promise deferred

我尝试使用诺言并在角度应用中推迟。

我使用了两个函数$scope.checkQuestions()$scope.saveExerciseApi() 但问题是第二个是在第一个完成之前启动的,这不是我的预期。

第一个调用承诺更新每个问题(使用REST服务) 然后更新页面上表单中使用的$scope.formQuestion[]数组。

$scope.Questions$scope.Exercises已经是promise对象,可以在REST服务中更新和创建实体。

$scope.formQuestion$scope.formexercise$scope.exercises是网页上使用的数据。

$scope.checkQuestions = function(){
deferred = $q.defer()
for (i in $scope.formQuestion){
    if ($scope.formQuestion[i].pk == null){     //Save
        $scope.Questions.add($scope.formQuestion[i]).then(function(newquestion){
            deferred.resolve(newquestion);
            $scope.formQuestion[i] = newquestion;
            });
        }    
    }
return deferred.promise;
}

$scope.saveExerciseApi = function() {
    if ($scope.formexercise.pk == null){        //Save
        $scope.Exercises.add($scope.formexercise).then(function(newexercise){
            $scope.exercises.push(newexercise);
            $scope.showform = false;
            });
        }
}

$scope.saveExercise = function() {
    $scope.checkQuestions().then($scope.saveExerciseApi);
}

编辑:

以下更改无法解决问题。

1)$scope.formexercise.questions仍然是空的

2)$ scope.saveExerciseApi启动从未发生

以下逻辑有什么问题吗?是否有更好,更清晰的方法来循环和更新questions的本地数据以及更新exercise数据之后?

$scope.checkQuestions = function(){
    deferred = $q.defer()
    $scope.formexercise.questions = Array ();
    for (i in $scope.formQuestion){                 
            if ($scope.formQuestion[i].pk == null){
            $scope.Questions.add($scope.formQuestion[i]).then(function(newquestion){
                $scope.formQuestion[i] = newquestion;
                $scope.formexercise.questions.push($scope.formQuestion[i].pk);
                if ($scope.formQuestion.length == i+1){
                deferred.resolve(newquestion);
                }
            });
          } else {
            $scope.Questions.edit($scope.formQuestion[i].pk, $scope.formQuestion[i]).then(function(updatequestion){
            $scope.formexercise.questions.push($scope.formQuestion[i].pk);
            if ($scope.formQuestion.length == i+1){
               deferred.resolve(udpatequestion);
            }
         });
        }
       }
return deferred.promise;
}

1 个答案:

答案 0 :(得分:2)

保存第一个问题后立即调用您的解决方法。在添加我相信的所有新问题后,应该调用resolve方法

$scope.checkQuestions = function(){
deferred = $q.defer()
var questionsToSave=0;
for (i in $scope.formQuestion){
    if ($scope.formQuestion[i].pk == null){     //Save
        int questionsToSave=questionsToSave + 1;
        $scope.Questions.add($scope.formQuestion[i]).then(function(newquestion){
            $scope.formQuestion[i] = newquestion;
            if(questionsToSave<=1)
               deferred.resolve(newquestion);
            else
               questionsToSave=questionsToSave-1;
            });
        }    
    }
return deferred.promise;
}