88description : Stream ReadableStream from Durable Objects.
99---
1010
11- import { GlossaryTooltip , WranglerConfig } from " ~/components" ;
11+ import { GlossaryTooltip , WranglerConfig , TypeScriptExample } from " ~/components" ;
1212
1313This example demonstrates:
1414
@@ -17,9 +17,11 @@ This example demonstrates:
1717- The Worker reads and logs the values from the stream.
1818- The Worker then cancels the stream after 5 values.
1919
20+ <TypeScriptExample >
2021``` ts
2122import { DurableObject } from ' cloudflare:workers' ;
2223
24+ // Send incremented counter value every second
2325async function * dataSource(signal : AbortSignal ) {
2426 let counter = 0 ;
2527 while (! signal .aborted ) {
@@ -35,17 +37,15 @@ export class MyDurableObject extends DurableObject<Env> {
3537 const abortController = new AbortController ();
3638
3739 const stream = new ReadableStream ({
38- start(controller ) {
40+ async start(controller ) {
3941 if (request .signal .aborted ) {
4042 controller .close ();
4143 return ;
4244 }
4345
44- (async () => {
45- for await (const value of dataSource (AbortSignal .any ([request .signal , abortController .signal ]))) {
46- controller .enqueue (new TextEncoder ().encode (String (value )));
47- }
48- })();
46+ for await (const value of dataSource (AbortSignal .any ([request .signal , abortController .signal ]))) {
47+ controller .enqueue (new TextEncoder ().encode (String (value )));
48+ }
4949 },
5050 cancel() {
5151 console .log (' Stream cancelled' );
@@ -91,6 +91,7 @@ export default {
9191 },
9292} satisfies ExportedHandler <Env >;
9393```
94+ </TypeScriptExample >
9495
9596:::note
9697
0 commit comments