-
Notifications
You must be signed in to change notification settings - Fork 5
Open
Description
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:
- The abort handler may only be called once
- Calling either resolve or reject makes all future calls to
promise.abort()
a no-op - The abort handler is automatically propagated to promises generated using
promise.then
- Edit:
promise.abort()
propagates to children (i.e. ifresolve
d with an abortable child promise,promise.abort()
will abort the child) - Callers can pass any arguments they wish through to the abort handler. This is helpful in a context-sensitive abort
- 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
Labels
No labels