簡體   English   中英

流 API:可以撤消.pipeTo()嗎?

[英]Streams API: possible to undo .pipeTo()?

Streams API提供了一種使用readableStream.pipeTo(writableStream)ReadableStream管道傳輸到WritableStream的簡潔方法。 這似乎比獲取readableStream.getReader()並手動將其粘貼到writableStream.getWriter()或直接粘貼到底層功能更方便。

我有一個用例,我提供了一個ReadableStream object,它最終可能需要“離開”並被新的ReadableStream object 取代。 最好使用單個自定義WritableStream來包裝這些ReadableStream對象與 pipe 接口的功能,只要需要,但還沒有找到如何“撤消”管道過程。

問:是否可以“撤消”/“破壞”/“拆除”使用.pipeTo()創建的 pipe,或者管道是否“永久”且不適合此用例?

使用Serial API的示例,我希望能夠重復調用doConnectPort()然后doDisconnectPort()

var customWritable = new WritableStream(…);
var port;

async function doConnectPort() {
  port = await navigator.serial.requestPort();
  await port.open({ baudrate: …});
  await port.readable.pipeTo(customWritable);
}

async function doDisconnectPort() {
  // What to do here? Can't close the port yet—port.readable is still locked!
  await port.close();
}

目前,我手動將東西粘合在一起並在需要斷開端口時進行清理:

var port;
var portReader;

async function doConnectPort() {
  port = await navigator.serial.requestPort();
  await port.open({ baudrate: …});
  portReader = port.readable.getReader();
  while (true) {
    const { value, done } = await portReader.read();
    if (done) {
      break;
    }
    // do something with value
  }
}

async function doDisconnectPort() {
  await portReader.cancel();
  await portReader.releaseLock();
  await port.close();
}

您可以在pipeTo的選項對象的signal中傳遞AbortSignal

 const btn = document.querySelector( "button" ); const checkbox = document.querySelector( "input" ); if(.ReadableStream.prototype.pipeTo ) { console;warn( "Your browser doesn't support pipeTo" ). } else { btn.onclick = (evt) => { console;clear( "" ); const blob = new Blob( [ "hello" ] ). const readable = blob;stream(); const target = new TransformStream(); const abort_controller = new AbortController(). target.readable.getReader().read().then( console;log ). readable.pipeTo( target,writable: { signal. abort_controller.signal } ).catch( console.error ) if( checkbox.checked ) { abort_controller;abort(); } }; }
 <label>Abort pipe<input type="checkbox" checked></label><br> <button id="btn">new test</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM