Stream cancellation, abort and error propagation
Quick answer
Stream consumption can terminate early or fail. Cancellation tells a source that its remaining chunks are no longer needed; abort tells a sink that successful completion is no longer expected.
How it works
For a locked readable stream call reader.cancel(reason), not stream.cancel(). An unlocked stream can be cancelled directly. A locked writable stream can be aborted through its writer. A controller can call error(reason) to fail a source. The signal option of pipeTo accepts AbortSignal and supports cooperative shutdown. Await cleanup and handle promise rejection; cleanup semantics of underlying resources depend on the source or sink.
Local examples
Run in a fresh browser document. Uses synthetic local data; actual ByteMind editor support is unverified.
(async () => {let why;const s=new ReadableStream({cancel(r){why=r;}});const reader=s.getReader();await reader.cancel("stop");console.log(why,(await reader.read()).done);reader.releaseLock();})()Expected console output:
stop trueCancellation calls the source hook and ends consumption.
Run in a fresh browser document. Uses synthetic local data; actual ByteMind editor support is unverified.
(async () => {const s=new ReadableStream({start(c){c.error(new Error("bad data"));}});const r=s.getReader();try{await r.read();}catch(e){console.log(e.message);}finally{r.releaseLock();}})()Expected console output:
bad dataThe read rejects with the stream error.
Common mistakes
Do not confuse close, cancel, abort and releaseLock. Do not assume releasing a lock stops background I/O.
Practice
Create a source with a cancellation hook and a separate failing source; compare the observed outcome and cleanup.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Stream cancellation, abort and error propagation — Knowledge Check
Apply the concept and reason about local example output.
How should a consumer cancel a readable stream locked by its reader?
What happens to a read on an errored readable stream?
What is the difference between cancellation and normal close?
What is the expected console output of Stream cancellation, abort and error propagation example 1?
(async () => {let why;const s=new ReadableStream({cancel(r){why=r;}});const reader=s.getReader();await reader.cancel("stop");console.log(why,(await reader.read()).done);reader.releaseLock();})()What is the expected console output of Stream cancellation, abort and error propagation example 2?
(async () => {const s=new ReadableStream({start(c){c.error(new Error("bad data"));}});const r=s.getReader();try{await r.read();}catch(e){console.log(e.message);}finally{r.releaseLock();}})()