Have multiple calls wait on the same promise in An

2019-06-26 10:37发布

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.

2条回答
等我变得足够好
2楼-- · 2019-06-26 11:12

$http already returns the promise for you, even more, in 2 useful types: success & error. So basically, the option that @kfis offered does NOT catch errors and not flexible. You could write something simple:

.factory('user', function($http) {
    return {
       getUser: function() {
          $http.get('/my/url/')
             .success(function(data) {
                return data;
             })
             .error(function(err) {
                // error handler
             })
       }
    }
})
查看更多
\"骚年 ilove
3楼-- · 2019-06-26 11:13

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;
            }
        }
    })
查看更多
登录 后发表回答