bluebird:取消promise.join不会取消孩子

时间:2014-06-10 23:46:22

标签: javascript promise bluebird cancellation

我使用bluebird.js作为比jquery延迟对象更好的promise对象。我希望能够做的是并行运行两个请求,当它们都完成后再运行一些代码。但我需要能够取消这两个请求。下面是一些突出显示我的问题的示例代码。当我运行它并在加入的promise上调用cancel函数时,我确实触及了join上的取消异常,但是没有在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();

1 个答案:

答案 0 :(得分: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(); 
});
相关问题