父母被取消时是否可以取消子女承诺?

问题描述 投票:1回答:3

我有这个代码(使用Bluebird Promise):

const promise = loadSomething(id)
  .then(something => {
    loadParentOfSomething(something.parentId);
    return something;
  });

当我然后做promise.cancel() getSomething被取消,但getSomethingParent不是。

有没有办法,当getSomething承诺被取消,我也可以得到getSomethingParent承诺取消?

两个加载函数都返回带有HTTP请求的可取消异步承诺,我想取消它们的原因是因为它们有时需要一段时间才能加载,例如当用户导航(SPA)时不再需要响应。

javascript promise bluebird cancellation
3个回答
0
投票

我想你在寻找什么

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解决后,这种取消也是可能的。


-1
投票

将函数定义为then回调的第二个参数。例:

const promise = getSomething(id)
  .then(something => {
    getSomethingParent(something.parentId);
    return something;
  }, error => {
    console.error(error)
  });

当你打电话给promise.reject()时,getSomethingParent将不会被召唤。 Reference


-2
投票

如果你准备参考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();
    });
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.