Revoking a Bluebird promise

Let's say I have the following promise chain:

var parentPromise = Promise.resolve()
  .then(function () {
    var condition = false;
    if (condition) {
      return parentPromise.cancel('valid reason');
    } else {
      return Promise.resolve()
        .then(function () {
          var someOtherCondition = true;
          if (someOtherCondition) {
            console.log('inner cancellation');
            return parentPromise.cancel('invalid reason');
          }
        });
    }
  })
  .catch(Promise.CancellationError, function (err) {
    console.log('throwing');
    if (err.message !== 'valid reason') {
      throw err;
    }
  })
  .cancellable();

      

The above is never included in catch

.

If we change condition

to true

, the internal undo will never be removed, but catch

still not triggered.

removing .cancellable

at the end and replacing all instances with parentPromise.cancel()

explicit throw new Promise.CancellationError()

"fixes" the problem. Why do not I understand?

Why didn't the original approach work?

I am using bluebird 2.3.11.

+3


source to share


1 answer


cancellable()

creates cancellation promises, and only they are thrown CancellationError

by default when the function is called cancel

for no reason.

In your case, you cancellable

only fulfill the promise after attaching the handler catch

. But the promise is not yet cancellable

. This way the function call cancel

will not raise Promise.CancellationError

.

You need to change your code structure like



then(function(..) {
    ...
})
.cancellable()
.catch(Promise.CancellationError, function (err) {
    ...
});

      

Note: I would recommend the promising one with its beautiful design construction Promise

. It is similar to the ECMA Script 6 specification.

new Promise(function(resolve, reject) {
    ...
});

      

+3


source







All Articles