1

sorry i cant show full code here, i came up with the following code snippet. I have a service and controller. In service, I added a 2 second timeout to my group service to test out spinner loading.

but somehow in controller, my code runs right away, without waiting for 2 seconds.

I did 3 break points, the order of execution i expected is : 2->1->3 but, it ended up with 2->3->1

Here is my service.

groupService.get = function() {
    var deffered = $q.defer();
    deffered.promise = $getMyDataStuffPromise.then(function (data) {
        $timeout(function() {
          deffered.resolve(); <- break point 1
        }, 2000);
    }, function (error) {
        deffered.reject();
        console.log('group error', error);
    });

    return deffered.promise; <- break point 2
};

controller:

   $q.all([
        PeopleSvc.get(),
        GroupSvc.get()
    ]).then(function(data){
           console.log('data returns, stop spinner'); <- break point 3
        });

could you please let me know what was wrong with this code? thanks!

innek
  • 114
  • 2
  • 13

2 Answers2

3

deffered.promise = is very weird (I don't know what else to call it).

But you should not even attempt to implement the deferrred antipattern. $timeout already returns a promise, so all you need to do here is to chain them:

groupService.get = function() {
    return $getMyDataStuffPromise.then(function (data) {
        return $timeout(function() {
            return undefined; // maybe data?
        }, 2000);
    });
};
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

Well the answer of this question is: you have assigned deferred.promise to the wrong thing, so it doesn't work

groupService.get = function() {
    var deffered = $q.defer(); // deferred.promise already generated here
    /*deffered.promise = */$getMyDataStuffPromise.then(function (data) {
        $timeout(function() {
          deffered.resolve();
        }, 2000);
    }, function (error) {
        deffered.reject();
        console.log('group error', error);
    });

    return deffered.promise;
};

A new promise object is already generated when you call $q.defer(), you re-assigned it to $getMyDataStuffPromise, of course it would resolve earlier. Just remove the assignment will do.

And sure, move away from promise-antipattern while you can, as suggested in other post.

Icycool
  • 7,099
  • 1
  • 25
  • 33