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!");
规范
规范 |
---|
流标准 # ref-for-ws-default-controller-signal① |
浏览器兼容性
BCD 表格仅在启用 JavaScript 的浏览器中加载。