Avoid multiple ajax requests angularJS

我是研究僧i 提交于 2019-12-05 10:52:35

You could just return the original promise if the request has already been made. Something like this should work;

myApp.factory('User', ['Restangular', '$q',
  function (Restangular, $q) {
    var deferred = false;

    return {
      getUser: function () {

        if(deferred) {
          return deferred.promise;
        }

        deferred = $q.defer();

        Restangular.all('user').getList().then(function (user) {
          deferred.resolve(user[0].email);
        });

        return deferred.promise;
      }
    };
  }
]);

Also have a look at the Restangular documentation for caching requests

Everytime you run getUser, a new defer is created for firstRun. If it's already ran, you call firstRun.then, but that promise is never resolved.

Thanks all for the answers, in the meanwhile I found a way to cache that particular factory:

.factory('User', ['Restangular', '$q',
  function (Restangular, $q) {
    var userCache, promises = [];
    return {

      getUser: function () {

        var deferred = $q.defer();

        if (promises.length > 0) {

          promises.push(deferred);

        } else if (!userCache) {

          promises.push(deferred);

          Restangular.all('user').getList().then(function (user) {
            var i;
            userCache = user[0];
            for (i = promises.length; i--;) {
              promises.shift().resolve(userCache);
            }
          });

        } else {

          deferred.resolve(userCache);

        }

        return deferred.promise;

      }
    };
  }
]);

Basically the idea is to create an array of promises while userCache is not ready, then resolve the whole queue once the request is ready and finally directly resolve the promise with the cached value for each future request.

I described the implementation of this promise caching here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!