Angular, reangular——如果有更多的当前搜索进来,就中止搜索调用



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

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

但我不认为这是你如何抓住它。我正在寻找一种方法来取消呼叫,如果有一个较新的呼叫,也许这是完全与承诺,而不是真正的重新排列?如有任何建议,我将不胜感激。谢谢你!

这实际上是一个很酷的问题,通常称为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);
});

最新更新