WritableStreamDefaultController: thuộc tính signal
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2023.
Note: This feature is available in Web Workers.
Thuộc tính chỉ đọc signal của giao diện WritableStreamDefaultController trả về AbortSignal liên kết với bộ điều khiển.
Giá trị
Một đối tượng AbortSignal.
Ví dụ
>Hủy bỏ một thao tác ghi dài
Trong ví dụ này, chúng ta mô phỏng một thao tác chậm bằng cách sử dụng một sink cục bộ: Chúng ta không làm gì khi một số dữ liệu được ghi ngoài việc chờ một giây. Điều này cho chúng ta đủ thời gian để gọi phương thức writer.abort() và từ chối promise ngay lập tức.
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!");
Chuyển AbortSignal xuống lớp cơ bản
Trong ví dụ này, chúng ta sử dụng Fetch API để thực sự gửi thông điệp đến máy chủ. Fetch API cũng hỗ trợ AbortSignal: Có thể sử dụng cùng một đối tượng cho cả phương thức fetch và WritableStreamDefaultController.
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!");
Thông số kỹ thuật
| Thông số kỹ thuật |
|---|
| Streams> # ref-for-ws-default-controller-signal①> |