Worker Using StreamWriter produces error
I am developing a worker that uses streams and am encountering some issues. I have reduced the code down to the following simple example to reproduce (one) of my problems. I have based it loosely off this : https://developers.cloudflare.com/workers/learning/using-streams/ with the difference being I want to write my own information to the response. Am I using streams correctly? I suspect I am not..
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
let { readable, writable } = new TransformStream();
const writer = writable.getWriter();
await writer.write((new TextEncoder()).encode("Hello"));
return new Response(readable, {headers: {"content-type":"application/json"}});
}
The error I am getting is:
A hanging Promise was canceled. This happens when the worker runtime is waiting for a Promise from JavaScript to resolve, but has detected that the Promise cannot possibly ever resolve because all code and events related to the Promise's I/O context have already finished.
17:37:07 POST / 200
✘ [ERROR] Uncaught (in response) Error: The script will never generate a response.1 Reply
The solution was
addEventListener("fetch", event => {
event.respondWith(handleRequest(event));
});
async function handleRequest(event) {
let { readable, writable } = new TransformStream();
const writer = writable.getWriter();
async function asyncWrite() {
writer.write((new TextEncoder()).encode("Hello"));
return writer.close();
};
event.waitUntil(asyncWrite());
return new Response(readable, {headers: {"content-type":"application/json"}});
}
Found it here: https://community.cloudflare.com/t/streaming-html/174322/2