我尝试使用诺言并在角度应用中推迟。
我使用了两个函数$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;
}
答案 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;
}