Chris Preston
Chris Preston

Reputation: 634

AngularJS promises don't execute in order

I can’t get my head around some of the promises. They work fine in some instances of my app, but in some they just never work.

In my controller, I have the following command:

   myFactory.redrawCategories()
        .then(myFactory.redrawTasks());

The redrawTasks function is called instantly, without waiting for the redrawCategories to finish.

The functions inside my factory look like this

   redrawTasks: function(){
        var defer = $q.defer();
        db.getAllDocs("task_").then(function(res) {

            angular.forEach(res, function(value){
               value = value.doc;
               tasks[value.category].push(value);
            });

            angular.forEach(tasks, function(taskArray, cat){
                // some code
            });

            defer.resolve(1);

        });

        return defer.promise;

    },

The other one is like

   redrawCategories: function(){

        var deferred = $q.defer();

        db.getAllDocs("category_").then(function(res) {

                var categoryArray = [];
                angular.forEach(res, function(value){
                    categoryArray.push(value.doc);
                });

                deferred.resolve("done");

        });


        return deferred.promise;

    },

Some of the unimortant code has been removed for better overview.

No idea really how to do it. I've tried putting the resolve() function just in front of the return but that doesn't work either.

I've read that sometimes you have to wrap things in a $scope.$apply, well in this case most likely a $rootScope.$apply as it's in the factory outside of the controller scope, but that doesn't really change it either, besides I haven't really grasped when something is "outside of Angular" as they describe that.

I've read a lot of examples and tutorials, but I just don't see the forest for the trees anymore.

Any help would be appreciated a lot. I'm so stuck with this :/ Thanks

Upvotes: 0

Views: 725

Answers (2)

ivarni
ivarni

Reputation: 17878

.then expects a function reference.

myFactory.redrawCategories()
    .then(myFactory.redrawTasks());

should be

myFactory.redrawCategories()
    .then(myFactory.redrawTasks);

When you have the () the function is executed immediately and .then is passed whatever it returned.

As noted in the comments, if you're relying on this in redrawTasks you'd do

myFactory.redrawCategories()
    .then(function() { 
       return myFactory.redrawTasks();
    });

Upvotes: 2

Pablojim
Pablojim

Reputation: 8582

Try:

myFactory.redrawCategories()
    .then(myFactory.redrawTasks);

You were calling the function. Instead you just want to pass it to then function and have angular call it.

Upvotes: 1

Related Questions