我必须使用restangular调用从服务中提取一些数据。服务器最近变慢了-所以我一直在寻找一种方法,如果有新的呼叫进入,则中止该呼叫(或者可能只是诺言),并告诉我的服务使用最近的呼叫。这是服务电话-
MySearchService.prototype.search = function(query) {
return $q(function(resolve, reject) {
var url = '/services/search';
Restangular.oneUrl(url, url)
.customPOST(query)
.then(resolve)
.catch(reject);
});
};
我在想类似
.withHttpConfig({hasNewSearch: abort.promise}) <<not sure you can put custom key in here
abort.resolve();
但是我不认为这是您的目标。我正在寻找一种方法来取消呼叫(如果有较新的呼叫),也许这完全是有希望的,而不是真的很麻烦吗?将不胜感激任何建议。谢谢!
这实际上是一个很酷的问题,通常称为last
或flatMapLatest
。
// we want something that takes a function and only cares about the last result
function last(fn){ // fn returns a promise
var lastValue = null; // the last promise to check against
return function(){
// call the function, and mark it as the last call
lastValue = fn.apply(this, arguments);
var p = lastValue;
return p.then(function validateLast(v){ // call the function, when it resolves
if(p === lastValue){ // if we're still the "last call" when we resolved
return v; // we're done, successful call
} else {
// a newer one came, resolve with it and verify no one came since
return lastValue.then(validateLast);
}
});
}
这会让你做类似的事情
MySearchService.prototype.search = last(function(query) {
// removed antipattern
return Restangular.oneUrl('/services/search', '/services/search')
.customPOST(query);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句