Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(insights): abort async query polling immediately on cancel (#86940)

posthog[bot]0277487bd962
diff --git a/frontend/src/lib/utils/async.test.ts b/frontend/src/lib/utils/async.test.ts
index b40da7173810..fe3f3b39c8c0 100644
--- a/frontend/src/lib/utils/async.test.ts
+++ b/frontend/src/lib/utils/async.test.ts
@@ -1,6 +1,15 @@
-import { PromiseTimeoutError, retryWithBackoff, withTimeout } from 'lib/utils/async'
+import { delay, PromiseTimeoutError, retryWithBackoff, withTimeout } from 'lib/utils/async'
describe('async utils', () => {
+ describe('delay()', () => {
+ it('rejects immediately when the signal is already aborted', async () => {
+ const controller = new AbortController()
+ controller.abort()
+
+ await expect(delay(10000, controller.signal)).rejects.toThrow('Aborted')
+ })
+ })
+
describe('withTimeout()', () => {
beforeEach(() => {
jest.useFakeTimers()
diff --git a/frontend/src/lib/utils/async.ts b/frontend/src/lib/utils/async.ts
index c30f19946bb2..d9e608857eee 100644
--- a/frontend/src/lib/utils/async.ts
+++ b/frontend/src/lib/utils/async.ts
@@ -4,13 +4,20 @@ export function makeDelay(ms: number): () => Promise<void> {
export function delay(ms: number, signal?: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
- const timeoutId = setTimeout(resolve, ms)
- if (signal) {
- signal.addEventListener('abort', () => {
- clearTimeout(timeoutId)
- reject(new DOMException('Aborted', 'AbortError'))
- })
+ if (signal?.aborted) {
+ reject(new DOMException('Aborted', 'AbortError'))
+ return
+ }
+ const onAbort = (): void => {
+ clearTimeout(timeoutId)
+ reject(new DOMException('Aborted', 'AbortError'))
}
+ // Remove the listener on resolve: pollForResults reuses one signal across many delay() calls
+ const timeoutId = setTimeout(() => {
+ signal?.removeEventListener('abort', onAbort)
+ resolve()
+ }, ms)
+ signal?.addEventListener('abort', onAbort, { once: true })
})
}