Kol*_*lby 8 javascript angularjs
我已经构建了一个通过$ http返回资源的复杂方法.
该方法返回一个promise,然后检查我的本地缓存是否存在资源.如果是,它将返回缓存的资源,如果不是,它将发出$ http请求.资源缓存后这很好用,但是我在加载时触及此方法的应用程序中有多个函数,并且每个函数都会生成http请求,因为资源尚未返回和缓存.
我想出了一个简单的检查来解决这个问题,但我觉得应该有一个更好的方法.我添加了一个布尔值,如果方法正在获取资源,则设置为true,如果是,我使用半秒超时解析方法,以给予请求时间解决.代码如下.
那么,有更好的方法吗?
var schools = [];
var loadingSchools = false;
function getAllSchools(forceUpdate) {
return $q(function (resolve, reject) {
if(loadingSchools) resolve($timeout(getAllSchools, 500));
else{
loadingSchools = true;
if (schools.length && !forceUpdate) {
loadingSchools = false;
resolve(schools);
return;
}
console.log('$http: Getting All Schools - schoolService.js');
$http.get(API_PATH + 'schools_GetAll', {cache:true})
.success(function(result) {
schools = result;
loadingSchools = false;
resolve(schools);
})
.error(function(error) {
schools = [];
loadingSchools = false;
reject(error);
});
}
});
}
Run Code Online (Sandbox Code Playgroud)
Igo*_*ush 24
首先,我认为没有必要将其HttpPromise纳入另一个承诺.不推荐使用这些success/error方法,您应该完全依赖于该方法,并将其视为常规承诺.then()HttpPromise
为了确保请求仅发送一次,您实际上可以跟踪HttpPromise您创建的第一个请求,并在随后的函数调用中返回相同的承诺.
这是一个接受API端点作为参数的服务,并确保只向该API发送一个请求.
app.factory('$httpOnce', [ '$http', '$cacheFactory',
function ($http, $cacheFactory) {
var cache = $cacheFactory('$httpOnce');
return function $httpOnce(url, options) {
return cache.get(url) || cache.put(url, $http.get(url, options)
.then(function (response) {
return response.data;
}));
};
}
]);
Run Code Online (Sandbox Code Playgroud)
用法
function log(data) {
console.log(data);
}
// issues an HTTP request
$httpOnce('https://api.github.com/').then(log);
// does not issue an HTTP request, returns the same promise as above
$httpOnce('https://api.github.com/').then(log);
// ...
// HTTP request completes somewhere, both promises above are resolved
// ...
setTimeout(function () {
// immediately resolved
$httpOnce('https://api.github.com/').then(log);
}, 5000);
Run Code Online (Sandbox Code Playgroud)
这是一个演示.您可以在开发工具中看到只发出一个请求.
| 归档时间: |
|
| 查看次数: |
5028 次 |
| 最近记录: |