我有这个代码(使用Bluebird Promise):
const promise = loadSomething(id)
.then(something => {
loadParentOfSomething(something.parentId);
return something;
});
当我然后做promise.cancel()
getSomething
被取消,但getSomethingParent
不是。
有没有办法,当getSomething
承诺被取消,我也可以得到getSomethingParent
承诺取消?
两个加载函数都返回带有HTTP请求的可取消异步承诺,我想取消它们的原因是因为它们有时需要一段时间才能加载,例如当用户导航(SPA)时不再需要响应。
我想你在寻找什么
const promise1 = loadSomething(id);
const promise2 = promise1.then(something => { return loadParentOfSomething(something.parentId); });
// ^^^^^^
promise2.catch(e => void "ignore"); // prevent unhandled rejections
然后你可以继续使用promise1
来访问结果,但也可以调用promise2.cancel()
。即使在promise1
解决后,这种取消也是可能的。
将函数定义为then
回调的第二个参数。例:
const promise = getSomething(id)
.then(something => {
getSomethingParent(something.parentId);
return something;
}, error => {
console.error(error)
});
当你打电话给promise.reject()
时,getSomethingParent
将不会被召唤。 Reference
如果你准备参考loadSomethingOfParent
的假承诺你应该能够在loadSomething
中取消它。
// Create a dummy promise to reference `loadParentOfSomething`
var dummyPromise = Promise.resolve();
// Pass `dummyPromise` to `loadSomething`
const promise = loadSomething(id, dummyPromise).then(something => {
dummyPromise = loadParentOfSomething(something.parentId);
return something;
});
loadSomething
将需要一个onCancel
处理程序,它将在取消承诺时执行。
function loadSomething(id, promise) {
return new Promise(function(resolve, reject, onCancel) {
// Do your stuff
// The `.cancel()` handler
onCancel(function() {
promise.cancel();
});
});
}