typescript 58 lines · 9 steps

A cancellable polling helper in TypeScript

A generic pollUntil repeatedly fetches until a condition holds, respecting a timeout and an AbortSignal.

Explained by highlit
1interface PollOptions<T> {
2 intervalMs?: number;
3 timeoutMs?: number;
4 signal?: AbortSignal;
5}
6 
7export async function pollUntil<T>(
8 fetchFn: () => Promise<T>,
9 isDone: (value: T) => boolean,
10 { intervalMs = 2000, timeoutMs = 60000, signal }: PollOptions<T> = {},
11): Promise<T> {
12 const deadline = Date.now() + timeoutMs;
13 
14 while (true) {
15 if (signal?.aborted) {
16 throw new DOMException("Polling aborted", "AbortError");
17 }
18 
19 const value = await fetchFn();
20 if (isDone(value)) {
21 return value;
22 }
23 
24 if (Date.now() + intervalMs >= deadline) {
25 throw new Error(`Condition not met within ${timeoutMs}ms`);
26 }
27 
28 await delay(intervalMs, signal);
29 }
30}
31 
32function delay(ms: number, signal?: AbortSignal): Promise<void> {
33 return new Promise((resolve, reject) => {
34 const timer = setTimeout(() => {
35 signal?.removeEventListener("abort", onAbort);
36 resolve();
37 }, ms);
38 
39 const onAbort = () => {
40 clearTimeout(timer);
41 reject(new DOMException("Polling aborted", "AbortError"));
42 };
43 
44 signal?.addEventListener("abort", onAbort, { once: true });
45 });
46}
47 
48export async function waitForJob(jobId: string): Promise<Job> {
49 return pollUntil(
50 async () => {
51 const res = await fetch(`/api/jobs/${jobId}`);
52 if (!res.ok) throw new Error(`Job fetch failed: ${res.status}`);
53 return (await res.json()) as Job;
54 },
55 (job) => job.status === "completed" || job.status === "failed",
56 { intervalMs: 1500, timeoutMs: 120000 },
57 );
58}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Generics let one polling loop serve any fetch shape while keeping return types precise.
  2. 2Wrapping setTimeout in a promise that also listens for abort makes delays cleanly cancellable.
  3. 3Checking the deadline before sleeping avoids waiting out a full interval you know will exceed the budget.

Related explainers

typescript
import { Injectable, signal, computed, effect, inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
 
export type Theme = 'light' | 'dark';

A signal-based theme service in Angular

signals reactivity dependency-injection
Intermediate 7 steps
typescript
import { Injectable } from '@angular/core';
import { HttpClient, HttpEventType, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, distinctUntilChanged, scan } from 'rxjs/operators';

Tracking upload progress in Angular

rxjs http-events state-reduction
Intermediate 8 steps
typescript
import { Component, HostBinding, Input } from '@angular/core';
 
type ProgressVariant = 'success' | 'warning' | 'danger';
 

A CSS-driven progress ring in Angular

host-bindings css-custom-properties input-setters
Intermediate 8 steps
typescript
import { Controller, Param, Sse, MessageEvent } from '@nestjs/common';
import { Observable, interval, merge } from 'rxjs';
import { filter, map, takeWhile } from 'rxjs/operators';
import { JobService } from './job.service';

Streaming job progress with SSE in NestJS

server-sent-events reactive-streams rxjs
Intermediate 8 steps
typescript
import {
  Controller,
  All,
  Req,

Catch-all routes and error shaping in NestJS

exception-handling routing middleware
Intermediate 6 steps
typescript
import {
  ArgumentsHost,
  Catch,
  ConflictException,

Turning TypeORM lock errors into 409s in NestJS

exception-handling optimistic-locking http-status
Intermediate 6 steps

Share this explainer

Here's the card — post it anywhere.

A cancellable polling helper in TypeScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code