start + pull mode — start() initializes resource, pull() reads from it
start + pull: simulated async resource
start() opens a simulated async resource (like a WebSocket / DB connection). It takes 1 second. Then pull() reads one "record" per call.
const stream = new ReadableStream({
start(controller) {
// simulate opening a connection — async
this.resource = openResourceAsync();
},
pull(controller) {
// wait until start's resource is ready
return this.resource.then(resource => {
const record = resource.readNext();
if (record) controller.enqueue(record);
else controller.close();
});
},
cancel(r) { this.resource?.then(r => r.close()); },
});
Consume
read() before start completes → waits. After start resolves, each read triggers pull which awaits the resource.then() — simulating a real async lookup.