蓝鸟:取消承诺.加入不会取消孩子

bluebird: Cancel on promise.join doesn't cancel children

本文关键字:取消 孩子 承诺 蓝鸟      更新时间:2023-09-26

我使用bluebird.js比jquery延迟对象更好的承诺对象。我想要能够做的是并行运行两个请求,当他们都完成,然后运行一些代码。但我需要这两个请求都能被取消。下面是一些示例代码,突出了我的问题。当我运行这个并在加入的承诺上调用取消函数时,我确实击中了join上的取消异常的catch,但不是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();

这里工作正常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(); 
});