Javascript 蓝鸟:取消承诺。加入不';不要取消孩子
我使用bluebird.js来实现比jquery延迟对象更好的promise对象。我希望能够并行运行两个请求,当它们都完成后,运行一些代码。但我需要这两个请求都能被取消。下面是一些突出我的问题的示例代码。当我运行这个函数并调用连接承诺上的cancel函数时,我确实找到了连接上的cancel异常,但在firstPromise或secondPromise上没有,因此ajax请求不会被中止。有人知道怎么做吗Javascript 蓝鸟:取消承诺。加入不';不要取消孩子,javascript,promise,bluebird,cancellation,Javascript,Promise,Bluebird,Cancellation,我使用bluebird.js来实现比jquery延迟对象更好的promise对象。我希望能够并行运行两个请求,当它们都完成后,运行一些代码。但我需要这两个请求都能被取消。下面是一些突出我的问题的示例代码。当我运行这个函数并调用连接承诺上的cancel函数时,我确实找到了连接上的cancel异常,但在firstPromise或secondPromise上没有,因此ajax请求不会被中止。有人知道怎么做吗 var firstAjax = someAjaxRequest(); var firstPro
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()
!我使用反模式是因为我是NoobXD。谢谢你指出这一点。至于双重ajax.abort,这是一个输入错误,应该是firstAjax.abort和secondAjax.abort,就像您提到的那样。但即使有这些更改,在加入时调用cancel似乎也不会取消加入的两个承诺。谢谢。这是我努力实现的一个很好的例子。是的,它是有效的。
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();
});