javascript 36 lines · 6 steps

Polling a job until it finishes in JavaScript

An async loop that repeatedly checks a job's status, with timeout and cancellation support.

Explained by highlit
1async function pollJobUntilComplete(jobId, { interval = 2000, timeout = 60000, signal } = {}) {
2 const deadline = Date.now() + timeout;
3 
4 while (true) {
5 const res = await fetch(`/api/jobs/${jobId}`, { signal });
6 if (!res.ok) {
7 throw new Error(`Failed to fetch job ${jobId}: ${res.status}`);
8 }
9 
10 const job = await res.json();
11 
12 switch (job.status) {
13 case 'completed':
14 return job.result;
15 case 'failed':
16 throw new Error(job.error || `Job ${jobId} failed`);
17 case 'pending':
18 case 'running':
19 break;
20 default:
21 throw new Error(`Unexpected status for job ${jobId}: ${job.status}`);
22 }
23 
24 if (Date.now() + interval >= deadline) {
25 throw new Error(`Timed out waiting for job ${jobId} after ${timeout}ms`);
26 }
27 
28 await new Promise((resolve, reject) => {
29 const timer = setTimeout(resolve, interval);
30 signal?.addEventListener('abort', () => {
31 clearTimeout(timer);
32 reject(new DOMException('Polling aborted', 'AbortError'));
33 }, { once: true });
34 });
35 }
36}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A while-true loop with await turns repeated network checks into readable sequential code.
  2. 2Threading an AbortSignal through both fetch and the delay makes the whole poll cancellable.
  3. 3Checking the deadline before sleeping avoids one pointless final wait past the timeout.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Polling a job until it finishes in JavaScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code