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

Angular, restangular - abort search call if more current one comes in

我必须使用 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();

但我不认为这就是你上钩的方式。如果有更新的呼叫,我正在寻找一种取消呼叫的方法,也许这完全是承诺,而不是真正的 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);
});