angular.js deferred doesnt work in callback

164 views
Skip to first unread message

Dima Vernovsky

unread,
May 24, 2013, 8:50:55 AM5/24/13
to ang...@googlegroups.com
Hello all! 

Maybe somone could help me:

I'm trying to use promises API to call server for json, now then i use resolve inside callback the promise doesn't work:

 .service('movieGetter', ['$q', '$timeout', function ($q, $timeout) {
    this.getData = function () {
        var deferred = $q.defer();
        $timeout(function(){
            mock.getData(function(data){
                deferred.resolve(data);
            });
        }, 2000);

        return deferred.promise;
    };
}]);

but, when i just call resolve from within the timout function everything works fine:
 .service('movieGetter', ['$q', '$timeout', function ($q, $timeout) {
    this.getData = function () {
        var deferred = $q.defer();
        $timeout(function () {

            deferred.resolve('test');
        }, 2000);

        return deferred.promise;
    };
}]);

Somone have eny idea maybe?

Thanks!

Kevin Sheppard

unread,
May 24, 2013, 3:37:16 PM5/24/13
to ang...@googlegroups.com
I faced a similar problem a while back. My solution was to inject $rootScope into your service and after your resolve the promise in the success callback of mock.getData(), call $rootScope.$apply();

Something like this:

$timeout(function(){
            mock.getData(function(data){
                deferred.resolve(data);
                $rootScope.$apply();
            });
        }, 2000);

Grant Rettke

unread,
May 28, 2013, 11:27:58 AM5/28/13
to ang...@googlegroups.com
There is some discussion about that need here, too:

http://docs.angularjs.org/api/ng.$q
> --
> You received this message because you are subscribed to the Google Groups
> "AngularJS" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to angular+u...@googlegroups.com.
> To post to this group, send email to ang...@googlegroups.com.
> Visit this group at http://groups.google.com/group/angular?hl=en-US.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>



--
Grant Rettke | ACM, AMA, COG, IEEE
gre...@acm.org | http://www.wisdomandwonder.com/
“Wisdom begins in wonder.” --Socrates
((λ (x) (x x)) (λ (x) (x x)))
“Life has become immeasurably better since I have been forced to stop
taking it seriously.” --Thompson
Reply all
Reply to author
Forward
0 new messages