ReadableStream.cancel() - Web APIs 编辑

The cancel() method of the ReadableStream interface cancels the associated stream. The supplied reason parameter will be given to the underlying source, which may or may not use it.

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

var promise = readableStream.cancel(reason);

Parameters

reason
A DOMString providing a human-readable reason for the cancellation.

Return value

A Promise, which fulfills with the value given in the reason parameter.

Exceptions

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

Examples

In Jake Archibald's cancelling a fetch 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.

var searchTerm = "service workers";
// Chars to show either side of the result in the match
var contextBefore = 30;
var contextAfter = 30;
var caseInsensitive = true;
var url = 'https://html.spec.whatwg.org/';

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

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

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

  var bytesReceived = 0;
  var buffer = '';
  var matchFoundAt = -1;

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

    bytesReceived += result.value.length;
    console.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) {
      console.log("Here's the match:")
      console.log(buffer.slice(
        Math.max(0, matchFoundAt - contextBefore),
        matchFoundAt + toMatch.length + contextAfter
      ));
      console.log("Cancelling fetch");
      reader.cancel();
      return;
    }
    else {
      console.log('Found match, but need more context…');
    }

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

Specifications

SpecificationStatusComment
Streams
The definition of 'cancel()' in that specification.
Living StandardInitial definition.

Browser compatibility

BCD tables only load in the browser

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:75 次

字数:5275

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文