ReadableStream: cancel() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2019.

Note: This feature is available in Web Workers.

The cancel() method of the ReadableStream interface returns a Promise that resolves when the stream is canceled.

Cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. That data is lost after cancel is called, and the stream is not readable any more. To read those chunks still and not completely get rid of the stream, you'd use ReadableStreamDefaultController.close().

Syntax

js
cancel()
cancel(reason)

Parameters

reason Optional

A human-readable reason for the cancellation. This is passed to the underlying source, which may or may not use it.

Return value

A Promise, which fulfills with undefined value.

Exceptions

TypeError

The stream you are trying to cancel is not a ReadableStream, or it is locked.

Examples

In the following example, a stream is used to fetch the WHATWG HTML spec chunk by chunk; each chunk is searched for the string "service workers". When the search terms is found, cancel() is used to cancel the stream — the job is finished so it is no longer needed.

html
<pre id="output"></pre>
js
const searchTerm = "service workers";
// Chars to show either side of the result in the match
const contextBefore = 30;
const contextAfter = 30;
const caseInsensitive = true;
const url = "https://html.spec.whatwg.org/";

log(`Searching '${url}' for '${searchTerm}'`);

fetch(url)
  .then((response) => {
    log("Received headers");

    const decoder = new TextDecoder();
    const reader = response.body.getReader();
    const toMatch = caseInsensitive ? searchTerm.toLowerCase() : searchTerm;
    const bufferSize = Math.max(toMatch.length - 1, contextBefore);

    let bytesReceived = 0;
    let buffer = "";
    let matchFoundAt = -1;

    return reader.read().then(function process(result) {
      if (result.done) {
        log("Failed to find match");
        return;
      }

      bytesReceived += result.value.length;
      log(`Received ${bytesReceived} bytes of data so far`);

      buffer += decoder.decode(result.value, { stream: true });

      // already found match & just context-gathering?
      if (matchFoundAt === -1) {
        matchFoundAt = (
          caseInsensitive ? buffer.toLowerCase() : buffer
        ).indexOf(toMatch);
      }

      if (matchFoundAt === -1) {
        buffer = buffer.slice(-bufferSize);
      } else if (
        buffer.slice(matchFoundAt + toMatch.length).length >= contextAfter
      ) {
        log("Here's the match:");
        log(
          buffer.slice(
            Math.max(0, matchFoundAt - contextBefore),
            matchFoundAt + toMatch.length + contextAfter,
          ),
        );
        log("Cancelling fetch");
        reader.cancel();
        return;
      } else {
        log("Found match, but need more context…");
      }

      // keep reading
      return reader.read().then(process);
    });
  })
  .catch((err) => {
    log(
      "Something went wrong. See devtools for details. Does the response lack CORS headers?",
    );
    throw err;
  });

Specifications

Specification
Streams
# ref-for-rs-cancel③

Browser compatibility

desktop mobile server
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Bun
Deno
Node.js
cancel
Chrome – Full support
Chrome 43 (Release date: 2015-05-19)
footnote Full support
Edge – Full support
Edge 14 (Release date: 2016-08-02)
footnote Full support
Firefox – Full support
Firefox 65 (Release date: 2019-01-29)
footnote Full support
Opera – Full support
Opera 30 (Release date: 2015-06-09)
footnote Full support
Safari – Full support
Safari 10.1 (Release date: 2017-03-27)
footnote Full support
Chrome Android – Full support
Chrome Android 43 (Release date: 2015-05-27)
footnote Full support
Firefox for Android – Full support
Firefox for Android 65 (Release date: 2019-01-29)
footnote Full support
Opera Android – Full support
Opera Android 30 (Release date: 2015-06-10)
footnote Full support
Safari on iOS – Full support
Safari on iOS 10.3 (Release date: 2017-03-27)
footnote Full support
Samsung Internet – Full support
Samsung Internet 4 (Release date: 2016-03-11)
footnote Full support
WebView Android – Full support
WebView Android 43 (Release date: 2015-05-27)
footnote Full support
WebView on iOS – Full support
WebView on iOS 10.3 (Release date: 2017-03-27)
footnote Full support
Bun – Full support
Bun 1 (Release date: 2023-09-08)
footnote Full support
Deno – Full support
Deno 1 (Release date: 2020-05-13)
footnote Full support
Node.js – Full support
Node.js 16.5 (Release date: 2021-07-14)
footnote Full support

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

See also