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:
- Am I using promises correctly?
- 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!