H W*_*H W 5 javascript promise cancellation angularjs angular-promise
题:
是否有一种"简单"的方法来取消AngularJS中的($q- /$http- )承诺或确定承诺得到解决的顺序?
例
我有一个长时间运行的计算,我通过请求结果$http.某些操作或事件要求我在$http解决初始承诺之前重新开始计算(从而发送新请求).因此,我想我不能使用像这样的简单实现
$http.post().then(function(){
//apply data to view
})
Run Code Online (Sandbox Code Playgroud)
因为我无法确保响应按照我发送请求的顺序返回 - 毕竟我想在所有承诺得到妥善解决时显示最新计算的结果.
但是我想避免等待第一个响应,直到我发送这样的新请求:
const timeExpensiveCalculation = function(){
return $http.post().then(function(response){
if (isNewCalculationChained) {return timeExpensiveCalculation();}
else {return response.data;}
})
}
Run Code Online (Sandbox Code Playgroud)
思考:
使用时,$http我可以访问响应上的config-object,使用一些时间戳或其他标识符来手动排序传入的响应.但是我希望我能以某种方式告诉角度取消过时的承诺,因此在解决时不会运行.then()函数.
如果没有$q-promises的手动实现,这不起作用$http.
也许只是拒绝承诺就是要走的路?但在这两种情况下,它可能需要永远,直到最终在生成下一个请求之前解决了一个promise(在此期间导致一个空视图).
是否存在一些我缺少的角度API函数,或者是否存在强大的设计模式或带有promise链接的"技巧"或$ q.all来处理返回"相同"数据的多个promise?
我通过生成 a 来做到这一点requestId,并在 promise 的then()函数中检查响应是否来自最新的requestId.
虽然这种方法实际上并没有取消之前的承诺,但它确实提供了一种快速简便的方法来确保您正在处理最近的请求响应。
就像是:
var activeRequest;
function doRequest(params){
// requestId is the id for the request being made in this function call
var requestId = angular.toJson(params); // I usually md5 hash this
// activeRequest will always be the last requestId sent out
activeRequest = requestId;
$http.get('/api/something', {data: params})
.then(function(res){
if(activeRequest == requestId){
// this is the response for last request
// activeRequest is now handled, so clear it out
activeRequest = undefined;
}
else {
// response from previous request (typically gets ignored)
}
});
}
Run Code Online (Sandbox Code Playgroud)
编辑:
附带说明一下,我想补充一点,这种跟踪概念requestId's也可以应用于防止重复请求。例如,在我的Data服务load(module, id)方法中,我做了一个这样的小过程:
requestId基于URL +参数。 签入请求哈希表 requestId
requestId未找到:生成新请求并将承诺存储在哈希表中requestId找到:只需从哈希表中返回承诺请求完成后,requestId从哈希表中删除的条目。
| 归档时间: |
|
| 查看次数: |
1330 次 |
| 最近记录: |