【发布时间】:2014-02-03 05:42:57
【问题描述】:
我试图避免对工厂中的服务器发出多个 ajax 请求。我已经添加了一个小的缓存服务,但是这还不够我的目标:在服务器响应之前,可以多次调用这个工厂,导致对服务器产生多个请求。
为了避免这种情况,我添加了第二个 promise 对象,如果 AJAX 请求已经执行并且对象尚未在缓存中,那么它应该等待第二个 promise 被解析,但看起来我错过了一些东西。
这是我的代码:
myApp.factory('User', ['Restangular', '$q',
function (Restangular, $q) {
var userCache, alreadyRun = false;
return {
getUser: function () {
var deferred = $q.defer(), firstRun= $q.defer();
if (!userCache && !alreadyRun) {
alreadyRun = true;
Restangular.all('user').getList().then(function (user) {
console.log('getting user live ');
userCache = user[0].email;
firstRun.resolve(user[0].email);
});
} else if (!userCache && alreadyRun) {
console.log('waiting for the first promise to be resolved ');
firstRun.then(function(user) {
console.log('resolving the promise');
deferred.resolve(userCache);
});
} else {
console.log('resolving the promise from the cache');
deferred.resolve(userCache)
}
return deferred.promise;
}
};
}
]);
【问题讨论】:
-
我在答案中添加了我的最终实现。