2

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

1 回答 1

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(); 
});
于 2014-06-11T07:05:34.127 回答