Note that there are some explanatory texts on larger screens.

plurals
  1. POChaining promise and defered with a for loop in angular application
    text
    copied!<p>I try to use promise and defered in an angular application.</p> <p>I use two functions <code>$scope.checkQuestions()</code> and <code>$scope.saveExerciseApi()</code> but the problem is that the second one is launched before the first has finished wich is not what I had expected.</p> <p>The first one call promises to update each questions (with a REST service) and then update <code>$scope.formQuestion[]</code> array which is used in a form on the page.</p> <p><code>$scope.Questions</code> and <code>$scope.Exercises</code> are already promise object to update and create entities in a REST service.</p> <p><code>$scope.formQuestion</code>, <code>$scope.formexercise</code>, <code>$scope.exercises</code> are data used on the webpage.</p> <pre><code>$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); } </code></pre> <p>EDIT:</p> <p>The following change doesn't fix the problem.</p> <p>1) <code>$scope.formexercise.questions</code> is still empty and </p> <p>2) $scope.saveExerciseApi launch never occured </p> <p>Is there anything wrong in the following logic ? Is there a better and cleaner way to loop over and update local data for <code>questions</code> and after to update <code>exercise</code> data ?</p> <pre><code>$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; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload