【问题标题】:bluebird: Cancel on promise.join doesn't cancel children蓝鸟:取消承诺。加入不会取消孩子
【发布时间】:2014-07-31 21:37:27
【问题描述】:

我将 bluebird.js 用于比 jquery 延迟对象更好的 promise 对象。我想要做的是并行运行两个请求,当它们都完成时运行一些代码。但我需要能够取消这两个请求。下面是一些突出显示我的问题的示例代码。当我运行它并在加入的承诺上调用取消函数时,我确实抓住了加入但不是在 firstPromise 或 secondPromise 上的取消异常,因此 ajax 请求不会中止。有谁知道如何做到这一点?

var firstAjax = someAjaxRequest();
var firstPromise = Promise.resolve(firstAjax)
.cancellable()
.catch(promise.CancellationError, function (e) {
    console.log("cancelled request");
    firstAjax.abort();
    throw e;
})
.catch(function (e) {
    console.log("caught " + e);
});

var secondAjax = someAjaxRequest();
var secondPromise = Promise.resolve(secondAjax)
.cancellable()
.catch(Promise.CancellationError, function (e) {
    secondAjax.abort();
    throw e;
})
.catch(function (e) {
    console.log("caught " + e);
});

var joinedPromise = Promise.join(firstPromise, secondPromise)
.cancellable()
.catch(Promise.CancellationError, function(e){
    firstPromise.cancel();
    secondPromise.cancel();
});

joinedPromise.cancel();

【问题讨论】:

  • 您的代码中包含延迟反模式,您的 secondPromise 函数不只是 Promise.resolve(someAjaxRequest()) 有什么原因吗?
  • 你为什么要打两次电话ajax.abort()?你应该有一个firstAjax.abort()和一个secondAjax.abort()
  • 我使用的是反模式,因为我是菜鸟 XD。感谢您指出了这一点。至于双 ajax.abort 是一个错字,应该是 firstAjax.abort 和 secondAjax.abort 就像你提到的。但即使有这些更改,在加入时调用取消似乎也不会取消加入的两个承诺。

标签: javascript promise bluebird cancellation


【解决方案1】:

这里工作正常http://jsfiddle.net/JHuJ3/

window.CancellationError = Promise.CancellationError;

var cancellableAjax = function() {
    var ret = $.ajax.apply($, arguments);
    return Promise.resolve(ret).cancellable().catch(CancellationError, function(e) {
        console.log("cancelled");
        ret.abort();
        throw e;
    });
};


var firstPromise = cancellableAjax();
var secondPromise = cancellableAjax();
var joinedPromise = Promise.join(firstPromise, secondPromise).cancellable().catch(CancellationError, function(e) {
    firstPromise.cancel();
    secondPromise.cancel();
});

Promise.delay(500).then(function() {
    joinedPromise.cancel(); 
});

【讨论】:

  • 谢谢。这是我试图实现的一个很好的例子。是的,它有效。
猜你喜欢
  • 2015-02-13
  • 2018-10-23
  • 2019-09-29
  • 2014-11-08
  • 1970-01-01
  • 2019-07-15
  • 2019-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多