首先,我认为没有必要将其包装HttpPromise
到另一个承诺中。在不赞成使用success/error
方法的情况下,您应该仅依靠该方法,并将当作常规承诺。then()``HttpPromise
为了确保只发送一次请求,您实际上可以跟踪HttpPromise
创建的第一个请求,并在随后的函数调用中返回相同的promise。
这是一项服务,它将接受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;
}));
};
}
]);
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);