Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have multiple calls wait on the same promise in Angular

I have multiple controllers on a page that use the same service, for the sake of example we will call the service USER.

The first time the USER.getUser() is called it does an $http request to GET data on the user. After the call is completed it stores the data in USER.data. If another call is made to USER.getUser() it checks if there is data in USER.data and if there is data it returns that instead of making the call.

My problem is that the calls to USER.getUser() happen so quickly that USER.data does not have any data so it fires the $http call again.

Here is what I have for the user factory right now:

.factory("user", function($http, $q){
    return {
        getUser: function(){
            var that = this;
            var deferred = $q.defer();
            if(that.data){
                deferred.resolve(that.data);
            } else {
                $http.get("/my/url")
                .success(function(res){
                    that.data = res;
                    deferred.resolve(that.data);
                });
            }
            return deferred.promise;
        }
    }
});

I hope my question makes sense. Any help would be much appreciated.

like image 440
Austin Lovell Avatar asked Apr 02 '15 19:04

Austin Lovell


1 Answers

Does this work for you?

.factory("user", function($http, $q) {
        var userPromise;

        return {
            getUser: function () {
                if (userPromise) {
                    return userPromise;
                }

                userPromise = $http
                    .get("/my/url")
                    .then(function(res) {
                        return res.data;
                    });

                return userPromise;
            }
        }
    })
like image 189
kfis Avatar answered Nov 15 '22 08:11

kfis