diff --git a/packages/stack/src/utils/sse-client.ts b/packages/stack/src/utils/sse-client.ts index 9abae81..065ac1e 100644 --- a/packages/stack/src/utils/sse-client.ts +++ b/packages/stack/src/utils/sse-client.ts @@ -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(); } - })(); + }); } /**