Merge branch 'sse-client-async' into 'development'

Resolve before loop but after starting stream reader

See merge request GeneralProtocols/xo/stack!40
This commit is contained in:
Jim Hamill
2025-03-12 02:56:56 +00:00
+17 -5
View File
@@ -78,10 +78,8 @@ export class SSEClient {
};
// Using an async IIFE to handle the connection without blocking
(async () => {
return new Promise(async (resolve) => {
try {
// TODO: We want to resolve only AFTER we handle connection.
// But this is not trivial!
const response = await fetch(this.url, fetchOptions);
if (!response.ok) {
@@ -101,8 +99,16 @@ export class SSEClient {
const decoder = new TextDecoder();
let buffer = '';
// Start the read here so we can resolve and then start handlng the stream
// We will await this at the start of the loop, and redeclare it at the end of each loop iteration
let readPromise = reader.read();
// Resolve before starting the loop so that we can start peforming other actions
// Keep this out of the loop to avoid flags or `already resolved` errors.
resolve();
while (true) {
const { done, value } = await reader.read();
const { done, value } = await readPromise;
if (done) {
this.connected = false;
@@ -126,6 +132,9 @@ export class SSEClient {
this.options.onMessage(event);
}
}
// Start reading the next chunk
readPromise = reader.read();
}
} catch (error) {
this.connected = false;
@@ -137,8 +146,11 @@ export class SSEClient {
if (this.options.onClose) {
this.options.onClose();
}
// Doesnt seem like you want to propagate the error here.
resolve();
}
})();
});
}
/**