取消承诺链?

编程入门 行业动态 更新时间:2024-10-23 01:42:17
本文介绍了取消承诺链?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我兑现了一系列承诺:

this.getData.then(this.getMoreData).then(this.getEvenMoreData);

在某个时候,用户可能决定取消该请求并请求其他请求.

At some point the user may decide to cancel the request and request something else.

如何取消链条的传播?

推荐答案

您必须检查每个链接方法中的状态(是否应该取消):

You'd have to check for the state (of whether you should cancel or not) inside each chained method:

var userRequestedCancel = false; this .getData() .then(function() { if(userRequestedCancel) { return Promise.reject('user cancelled'); } return getMoreData(); }) .then(function() { if(userRequestedCancel) { return Promise.reject('user cancelled'); } return getEvenMoreData(); })

或者也许是一种稍微更优雅的方式(已编辑为将上下文和参数传递给callback方法)

Or perhaps a slightly more elegant way (edited to pass context and arguments to callback methods)

var currentReq = false; var userRequestedCancel = false; var shouldContinue = function(cb,args) { if(userRequestedCancel) { return Promise.reject('user cancelled'); } currentReq = cb.apply(this,args); return currentReq; } var onCancel = function() { userRequestedCancel = true; currentReq && currentReq.abort(); } this .getData() .then(function() { return shouldContinue(getMoreData,arguments); }) .then(function() { return shouldContinue(getEvenMoreData,arguments); })

如果您还需要取消当前请求(这很简单),请将当前的ajax请求设置为全局变量,并且无论将userRequestedCancel标志设置为true的哪个事件,也都可以取消ajax请求(请参见上面的编辑代码)

If you need to cancel the current request as well, that is kind of trivial, set your current ajax request to be a global variable, and whatever event sets the userRequestedCancel flag to true, have that also cancel the ajax request (see edited code above)

更多推荐

取消承诺链?

本文发布于:2023-11-25 02:47:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628016.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!