链接承诺并用延迟执行在角应用环(Chaining promise and defered with

2019-10-19 01:15发布

我尝试使用的承诺,在角度应用延迟执行。

我用两个函数$scope.checkQuestions()$scope.saveExerciseApi()但问题是,之前,首先完成至极并不是我预期的第二个启动。

第一个呼叫承诺更新每个问题(与REST服务),然后更新$scope.formQuestion[]数组其在页面上的形式使用。

$scope.Questions$scope.Exercises已经答应对象更新,并在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;
}

Answer 1:

您解决方法被调用,一旦第一个问题被保存。 该解决方法应该将所有的新的问题,我相信之后调用

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


文章来源: Chaining promise and defered with a for loop in angular application