ReadableStreamDefaultController

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流瀏覽器均已支援。

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

ReadableStreamDefaultController 介面是 Streams API 的一部分,它表示一個控制器,允許控制 ReadableStream 的狀態和內部佇列。預設控制器適用於非位元組流。

建構函式

無。ReadableStreamDefaultController 例項在 ReadableStream 構建期間自動建立。

例項屬性

ReadableStreamDefaultController.desiredSize 只讀

返回填充流內部佇列所需的期望大小。

例項方法

ReadableStreamDefaultController.close()

關閉關聯的流。

ReadableStreamDefaultController.enqueue()

將給定的塊排隊到關聯的流中。

ReadableStreamDefaultController.error()

導致與關聯流的任何未來互動都發生錯誤。

示例

在下面的簡單示例中,使用建構函式建立了一個自定義的 ReadableStream(有關完整程式碼,請參閱我們的 簡單隨機流示例)。start() 函式每秒生成一個隨機文字字串並將其入隊到流中。還提供了一個 cancel() 函式,以便在出於任何原因呼叫 ReadableStream.cancel() 時停止生成。

請注意,ReadableStreamDefaultController 物件會作為 start()pull() 函式的引數提供。

當按下按鈕時,生成停止,使用 ReadableStreamDefaultController.close() 關閉流,並執行另一個函式,該函式將資料從流中讀回。

js
let interval;
const stream = new ReadableStream({
  start(controller) {
    interval = setInterval(() => {
      let string = randomChars();

      // Add the string to the stream
      controller.enqueue(string);

      // show it on the screen
      let listItem = document.createElement("li");
      listItem.textContent = string;
      list1.appendChild(listItem);
    }, 1000);

    button.addEventListener("click", () => {
      clearInterval(interval);
      fetchStream();
      controller.close();
    });
  },
  pull(controller) {
    // We don't really need a pull in this example
  },
  cancel() {
    // This is called if the reader cancels,
    // so we should stop generating strings
    clearInterval(interval);
  },
});

規範

規範
Streams
# rs-default-controller-class

瀏覽器相容性

另見