Skip to content

AbortablePromise #12

@mjackson

Description

@mjackson

I'm currently using an AbortablePromise class that I wrote for mach with good results. The API is very simple (adds only one argument to your resolver), transparently supports propagation, and doesn't make any assumptions about whether the promise is fulfilled or rejected when you abort. Also, only one new property/method is exposed on promise objects, promise.abort.

Here's an example of what it looks like to use it:

var promise = new AbortablePromise(function (resolve, reject, onAbort) {
  // Use resolve & reject as you normally would.
  var request = makeRequest( ... , function (error, response) {
    if (error) {
      reject(error);
    } else {
      resolve(response);
    }
  });

  // Use onAbort to register a promise.abort() function. It is the
  // responsibility of this function to abort the execution of the
  // promise and resolve/reject as needed.
  onAbort(function () {
    request.abort();
    reject(new Error('Request was aborted'));
  });
});

promise.abort(); // Calls the onAbort handler.

The implementation currently makes following guarantees:

  1. The abort handler may only be called once
  2. Calling either resolve or reject makes all future calls to promise.abort() a no-op
  3. The abort handler is automatically propagated to promises generated using promise.then
  4. Edit: promise.abort() propagates to children (i.e. if resolved with an abortable child promise, promise.abort() will abort the child)
  5. Callers can pass any arguments they wish through to the abort handler. This is helpful in a context-sensitive abort
  6. If the abort handler throws, the promise is rejected

It's fairly easy to layer this on top of existing promise implementations since the Promise constructor doesn't require any extra arguments, only the resolver.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions