如何销毁未解决的承诺 [英] How to destroy unresolved promise

查看:29
本文介绍了如何销毁未解决的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看代码片段

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

这里的 getSongList 只是通过 HTTP 请求从服务器返回歌曲列表.

Here getSongList simply returns list of songs from server by an HTTP request.

在我的 HTML 中:

And in my HTML:

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

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

The problem here is with behaviour of promises, sometimes if some promise takes more time(even in ms.) to get resolved then it shows false data. when you search for 'AKON' lets say promise with first strike 'A' returns last then it refreshes the scope with false data, Is there any way to stop or discard promise which have not been resolved before sending another promise to server, or how can I handle such kind of scenario.

提前致谢.

推荐答案

$http 调用可以取消,方法是在 'timeout' 配置选项中传递一个 promise,并解决这个 promise.

$http calls can be cancelled, by passing a promise in the 'timeout' config option, and resolving that promise.

来自文档:

timeout – {number|Promise} – 以毫秒为单位的超时时间,或承诺在解决时应中止请求.

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

这篇关于如何销毁未解决的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆