我提供的服务可能需要超过一分钟的时间并返回一些数据。这是服务代码的一部分。
var deferred = $q.defer();
//check data is in cache
//if not, some process (take some time)
deferred.resolve( data);
});
return deferred.promise;并试图在连续两个js文件上使用此服务。这是调用服务的js代码的一部分。
myService.get().then( function( data) { //works });它应该是这样工作的。
加载A.js ->服务加载-> get数据(花费一些时间) ->保存缓存中的数据->进程A.js ->负载B.js ->服务加载->从缓存-> process B.js获取数据
但是,由于A.js和B.js文件几乎同时加载,这就是当前的工作方式。
加载A.js ->服务负载->获取数据(花费一些时间) ->,同时加载B.js ->服务负载-> 获取数据(花费一些时间)重复加载数据 -> .
如果A.js或B.js服务中有一个已经在使用服务,我应该如何挂起它们?
发布于 2016-04-18 03:06:45
我最近也遇到了同样的问题。这是我为解决这个问题所做的。
这个想法是创建一个标志来识别一个http请求是否仍在进行中,并使用$timeout重试直到解决了以前的请求。在进行重试之前,将立即返回延迟对象,但稍后将进行解析。
就像这样,为你服务:-
var httpInProgress = false; // used to identify if a request is still in progress
//this is your service method
service.loadData = function(yourParam, defer, shouldNotReturn){
if(!defer){
defer = $q.defer();
}
if(httpInProgress){
//if http already in progress, retry again with the same defer object.
$timeout(function(){service.loadData(yourParam, defer, true);}, 100);
if(!shouldNotReturn){
//return a promise but resolve later when we actual deal with http
return defer.promise;
}
}else{
//do normal stuff if no http in progress
service.sendActualRequest();
}
};
service.sendActualRequest = function(yourParam, defer){
httpInProgress = true;
$http(request).then(function(res){
defer.resolve(res);
}, function(err){
defer.reject(err);
}).finally(function(){
httpInProgress = false;
});
return defer.promise;
};https://stackoverflow.com/questions/36683977
复制相似问题