JAVASCRIPT

Polling an API for Asynchronous Job Completion Status

Efficiently monitor the status of long-running backend jobs by implementing a polling mechanism to periodically check an API endpoint until the job is completed or a timeout occurs.

async function pollJobStatus(jobId, checkUrl, interval = 2000, timeout = 60000) {
  const startTime = Date.now();

  return new Promise((resolve, reject) => {
    const poll = async () => {
      if (Date.now() - startTime > timeout) {
        return reject(new Error('Polling timed out.'));
      }

      try {
        const response = await fetch(`${checkUrl}/${jobId}`);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const statusData = await response.json();

        if (statusData.status === 'completed') {
          resolve(statusData.result);
        } else if (statusData.status === 'failed') {
          reject(new Error(`Job ${jobId} failed: ${statusData.message}`));
        } else {
          // Still pending, poll again
          setTimeout(poll, interval);
        }
      } catch (error) {
        console.warn(`Polling error for job ${jobId}:`, error.message);
        setTimeout(poll, interval); // Attempt to poll again despite temporary errors
      }
    };
    poll();
  });
}

// Example usage (assuming a backend that returns { status: 'pending'|'completed'|'failed', result?: any, message?: string })
// pollJobStatus('job123', 'https://api.example.com/job-status')
//   .then(result => console.log('Job completed with result:', result))
//   .catch(error => console.error('Polling error:', error));

// Simulating a backend that returns a pending status for a few seconds then completes
// setTimeout(() => console.log('Simulating job completion'), 6000);
How it works: This JavaScript snippet demonstrates an API polling mechanism useful for checking the status of asynchronous backend jobs. The `pollJobStatus` function repeatedly makes requests to a specified `checkUrl` for a given `jobId` at a set `interval`. It continues polling until the job status indicates 'completed' (resolving the promise with the result) or 'failed' (rejecting the promise), or if a `timeout` is reached. This pattern is essential when a backend process is long-running and doesn't use real-time communication like WebSockets.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs