如何摧毁未完成的承诺

How to destroy unresolved promise

查看代码片段

$scope.getSongs = function(keyword){
     songServices.getSongList(keyword).then(
         function(resp){
             $scope.songList = resp.data.songList;
         }
     );
}

此处 getSongList 只是通过 HTTP 请求 returns 来自服务器的歌曲列表。

在我的 HTML 中:

<input auto-focus type="text" placeholder="Enter song ID/Keyword" ng-model="keyword" ng-change="getSongs()">

这里的问题在于承诺的行为,有时如果某些承诺需要更多时间(甚至以毫秒为单位)才能得到解决,那么它会显示错误数据。当您搜索 'AKON' 时,让我们说 promise with first strike 'A' returns last 然后它用错误数据刷新范围,有没有办法停止或丢弃之前未解决的承诺向服务器发送另一个承诺,或者我该如何处理这种情况。

提前致谢。

可以通过在 'timeout' 配置选项中传递承诺并解决该承诺来取消 $http 调用。

来自the documentation

timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.

示例:

var canceler = $q.defer();
$http.get(someUrl, { timeout: canceler.promise });

// later: cancel the http request

canceler.resolve();

与其破坏承诺,不如在用户停止输入之前不要拨打电话。您可以使用 ng-options 指令来设置去抖动计时器。这样操作只会在用户停止输入后执行。

<input auto-focus type="text" placeholder="Enter song ID/Keyword" ng-model="keyword" ng-change="getSongs" ng-model-options="{ debounce: 500}">

您可以很容易地从一个普通的 promise 创建一个可销毁的 promise:

var destroyablePromise = function(p) {
  var r = $q.defer();

  p.then(function(a) { if (p) { r.resolve(a); }}, 
         function(a) { if (p) { r.reject(a); }},
         function(a) { if (p) { r.notify(a); }});

  r.promise.destroy = function() {
    p = null;
  };
  return r.promise;
}

瞧瞧!