Skip to content

Background #1

@ForbesLindesay

Description

@ForbesLindesay

Cancellation has not yet been put into any of the major JavaScript promise libraries as far as I'm aware.

The only promise library to have any cancellation support is when.js. There has however also been some prior art in the form of C# cancellation tokens. There are a few things to decide upon.

Triggering Cancellation

We need to decide how cancellation is triggered. This is probably as simple as a cancel method on the returned promise. The only problem with doing that is you can't then give a promise (as the result of a function) to multiple mutually suspicious receivers. C# does it with a separate CancellationTokenSource object. The relation between CancellationToken and CancellationTokenSource is analogous to the relationship between promise and resolver.

Handling Cancellation

It is easy enough to cancel the resolution of the promise, but there also needs to be a way to handle cancellation of the underlying operation (e.g. downloading a file from a web server). C# provides a CancellationToken to the function, which has methods for testing whether cancellation has been requested and for adding an event handler to be triggered when the operation is cancelled.

Propagating cancellation

Cancellation should propagate to any underlying asyncronous operations. This process has to be controlled carefully though, because there may be points where you don't want to support cancellation. C# supports cancellation by letting you simply pass on the CancellationToken to another asynchronous operation.

Correct Behaviour

When a task is cancelled in C# it is rejected with an OperationCancelledException. Alternatives would be to simply never resolve the promise, or resolve the promise imediately with undefined or null. It could also be thought of as an additional state (pending/fulfilled/rejected/cancelled)

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