0

This may or may not be a dumb question, or perhaps I have not fully wrapped my mind around angularjs promises yet. But basically I have some functionality on my front end to move items in a list (called components) up and down based off button click in this case I will only use moveUp to demonstrate my issue.

$scope.moveUp = function(){ 
//do some work based off obj clicked

//call my put request to change order of components in my db
componentFactory.putData(data).then(

  componentFactory.getData().then(function(response){
   $scope.currentComponents = response.data;
  },
   function(error){
   console.error(error);
  }));
}

So my logic for this code is that I need to update the order of the components in the database, then call a get request to get the new updated list of components then display them.

The issue that I am experiencing is that every couple of clicks, the db list will not update. This is due to the fact that my first promise is not resolving until after my get request, so it returns a 304 not modified.

My factory looks as follows:

 app.factory('componentFactory',['$q',function($q){

 return{

 getComponents:function(){
        var deffered = $q.defer();
        httpPromise = $http.get('/components');

        httpPromise.then(function(response){
                deffered.resolve(response);
        },
        function(error) {
            console.error(error);
        });
            return deffered.promise;

      },


      putData: function(data){
           var deffered = $q.defer();
           httpPromise = $http.put('/components',data);

           httpPromise.then(function(response){
                deffered.resolve(response);
           },
            function(error) {
            console.error(error);
        });
            return deffered.promise;

      }

On the server side, my put request is merely manipulating a mongodb collection with collection.update() to the field with the order and returning a status code based off if it worked or not.

Questions:

  1. Am I using promises correctly?
  2. Why is the promise of the put data not resolving until after my get request in some cases?

I appreciate any help I can get. Thank you!

  • In the first part of your code snippet, can you wrap " componentFactory.getData().then(function(response)" in a function like other calls? And in my impression, the outer promise will pass result to inner promise, so why are you saying inner promise returns first? – ABOS Apr 13 '15 at 22:45
  • See [Is this a “Deferred Antipattern”?](http://stackoverflow.com/questions/30750207/is-this-a-deferred-antipattern). – georgeawg Mar 31 '17 at 14:23

0 Answers0