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① |
浏览器兼容性
加载中…