WritableStreamDefaultController:signal 屬性
注意:此功能在 Web Workers 中可用。
WritableStreamDefaultController 介面的只讀屬性 signal 返回與該控制器關聯的 AbortSignal 物件。
值
一個 AbortSignal 物件。
示例
中止長時間寫入操作
在此示例中,我們使用本地接收器模擬慢速操作:當寫入一些資料時,我們不做任何事情,只是等待一秒鐘。這給了我們足夠的時間來呼叫 writer.abort() 方法並立即拒絕 promise。
js
const writingStream = new WritableStream({
// Define the slow local sink to simulate a long operation
write(chunk, controller) {
return new Promise((resolve, reject) => {
controller.signal.addEventListener("abort", () =>
reject(controller.signal.reason),
);
// Do nothing but wait with the data: it is a local sink
setTimeout(resolve, 1000); // Timeout to simulate a slow operation
});
},
});
// Perform the write
const writer = writingStream.getWriter();
writer.write("Lorem ipsum test data");
// Abort the write manually
await writer.abort("Manual abort!");
將 AbortSignal 轉移到底層
在此示例中,我們使用 Fetch API 將訊息實際傳送到伺服器。Fetch API 也支援 AbortSignal:可以將相同的物件用於 fetch 方法和 WritableStreamDefaultController。
js
const endpoint = "https://www.example.com/api"; // Fake URL for example purpose
const writingStream = new WritableStream({
async write(chunk, controller) {
// Write to the server using the Fetch API
const response = await fetch(endpoint, {
signal: controller.signal, // We use the same object for both fetch and controller
method: "POST",
body: chunk,
});
await response.text();
},
});
// Perform the write
const writer = writingStream.getWriter();
writer.write("Lorem ipsum test data");
// Abort the write manually
await writer.abort("Manual abort!");
規範
| 規範 |
|---|
| Streams # ref-for-ws-default-controller-signal① |
瀏覽器相容性
載入中…