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:
@@ -78,10 +78,8 @@ export class SSEClient {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Using an async IIFE to handle the connection without blocking
|
// Using an async IIFE to handle the connection without blocking
|
||||||
(async () => {
|
return new Promise(async (resolve) => {
|
||||||
try {
|
try {
|
||||||
// TODO: We want to resolve only AFTER we handle connection.
|
|
||||||
// But this is not trivial!
|
|
||||||
const response = await fetch(this.url, fetchOptions);
|
const response = await fetch(this.url, fetchOptions);
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
@@ -101,8 +99,16 @@ export class SSEClient {
|
|||||||
const decoder = new TextDecoder();
|
const decoder = new TextDecoder();
|
||||||
let buffer = '';
|
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) {
|
while (true) {
|
||||||
const { done, value } = await reader.read();
|
const { done, value } = await readPromise;
|
||||||
|
|
||||||
if (done) {
|
if (done) {
|
||||||
this.connected = false;
|
this.connected = false;
|
||||||
@@ -126,6 +132,9 @@ export class SSEClient {
|
|||||||
this.options.onMessage(event);
|
this.options.onMessage(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Start reading the next chunk
|
||||||
|
readPromise = reader.read();
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.connected = false;
|
this.connected = false;
|
||||||
@@ -137,8 +146,11 @@ export class SSEClient {
|
|||||||
if (this.options.onClose) {
|
if (this.options.onClose) {
|
||||||
this.options.onClose();
|
this.options.onClose();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Doesnt seem like you want to propagate the error here.
|
||||||
|
resolve();
|
||||||
}
|
}
|
||||||
})();
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Reference in New Issue
Block a user