diff --git a/packages/sdk/src/query_on_connect/query_on_connect.ts b/packages/sdk/src/query_on_connect/query_on_connect.ts index 2fc16e9a4b..7d1c4dddaf 100644 --- a/packages/sdk/src/query_on_connect/query_on_connect.ts +++ b/packages/sdk/src/query_on_connect/query_on_connect.ts @@ -54,6 +54,7 @@ export class QueryOnConnect< private isRunning: boolean = false; private abortController?: AbortController; + private activeQueryPromise?: Promise; private boundStoreConnectHandler?: (event: CustomEvent) => void; private boundHealthHandler?: (event: CustomEvent) => void; @@ -87,7 +88,7 @@ export class QueryOnConnect< this.setupEventListeners(); } - public stop(): void { + public async stop(): Promise { if (!this.isRunning) { return; } @@ -99,6 +100,15 @@ export class QueryOnConnect< this.abortController = undefined; } + if (this.activeQueryPromise) { + log.info("Waiting for active query to complete..."); + try { + await this.activeQueryPromise; + } catch (error) { + log.warn("Active query failed during stop:", error); + } + } + this.unsetEventListeners(); } @@ -130,7 +140,10 @@ export class QueryOnConnect< this.lastTimeOffline > this.lastSuccessfulQuery || timeSinceLastQuery > this.forceQueryThresholdMs ) { - await this.query(peerId); + this.activeQueryPromise = this.query(peerId).finally(() => { + this.activeQueryPromise = undefined; + }); + await this.activeQueryPromise; } else { log.info(`no querying`); }