ReadableStream: cancel() 方法

Baseline 已广泛支持

此功能已成熟,并可在多种设备和浏览器版本上使用。自 ⁨2019 年 1 月⁩起,它已在所有浏览器中可用。

注意:此功能在 Web Workers 中可用。

ReadableStream 接口的 cancel() 方法返回一个 Promise,该 Promise 在流被取消时解析。

当您已完全完成流的处理,不再需要从中读取任何数据时,可以使用 cancel。即使有等待读取的已入队块(chunks),这些数据在调用 cancel 后也会丢失,流也不再可读。要仍然读取这些块而不完全丢弃流,您应该使用 ReadableStreamDefaultController.close()

语法

js
cancel()
cancel(reason)

参数

reason 可选

用于取消的可读的理由。这会被传递给底层源(underlying source),底层源可能会也可能不会使用它。

返回值

一个 Promise,它会以 undefined 值 fulfilled。

异常

TypeError

您尝试取消的流不是 ReadableStream,或者它已被锁定。

示例

在下面的示例中,一个流被用来逐块获取 WHATWG HTML 规范;每个块都会被搜索字符串 "service workers"。当找到搜索词时,会使用 cancel() 方法取消流——任务已完成,因此不再需要它。

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.whatwg.cn/";

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;
  });

规范

规范
Streams
# ref-for-rs-cancel③

浏览器兼容性

另见