我兑现了一系列承诺:
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)
更多推荐
取消承诺链?
发布评论