gpt4 book ai didi

javascript - Angular, restangular - 如果有更多当前的搜索调用,则中​​止搜索调用

转载 作者:行者123 更新时间:2023-11-30 16:44:33 25 4
gpt4 key购买 nike

我必须使用 restangular 调用从服务中提取一些数据。服务器最近变慢了 - 所以我正在寻找一种方法来在有新调用进入时可能中止调用(或者可能只是 promise )并告诉我的服务使用最近的调用。这是服务电话 -

  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();

但我不认为这是你 Hook 的方式。如果有更新的调用,我正在寻找一种取消调用的方法,也许这完全是 promise ,而不是真正的 restangular 吗?将不胜感激任何建议。谢谢!

最佳答案

这实际上是一个很酷的问题,通常称为lastflatMapLatest

// 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);
});

关于javascript - Angular, restangular - 如果有更多当前的搜索调用,则中​​止搜索调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31433015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com