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

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

问题描述

看看代码片段

$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中:

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

这里的问题是promise的行为,有时如果某个promise需要花费更多时间(甚至以毫秒为单位)来解决,那么它会显示错误的数据.当您搜索"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调用可以通过在超时"配置选项中传递承诺并解决该承诺而取消.

$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天全站免登陆