When handling a stream response with a content-type of text/event-stream
using fetch
, reader
, and decoder
, it seems that the reader only returns after all chunks are received. I expected the reader to return as soon as each chunk is received. Am I approaching the stream response handling incorrectly?
const sseController = new AbortController();
fetch(url, {
method: 'POST',
mode: 'cors',
credentials: 'include',
headers: {
Accept: 'text/event-stream,application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
...params,
}),
signal: sseController.signal,
}).then(async (response) => {
console.log('sselog::: open', new Date());
if (!response.ok || !response.body) {
// TODO onerror
return;
}
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
while (true) {
const { done, value } = await reader?.read();
console.log('sselog::: while', value);
const str = new TextDecoder().decode(value);
// TODO onmessage
if (done) {
return;
}
}
});
The sselog::: while
output shows only one iteration, but in reality, the backend received two messages with types major
and message
.
https://i.sstatic.net/n6jZD.png