JAVASCRIPT

Polling API for Asynchronous Job Status

Learn to effectively poll an API endpoint in JavaScript to check the status of a long-running asynchronous job, ensuring timely updates without blocking the UI.

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 data = await response.json();

        if (data.status === 'completed') {
          resolve(data.result);
        } else if (data.status === 'failed') {
          reject(new Error(data.message || 'Job failed.'));
        } else {
          // Not completed or failed, poll again
          setTimeout(poll, interval);
        }
      } catch (error) {
        console.error('Polling error:', error);
        setTimeout(poll, interval); // Retry polling on network/parsing error
      }
    };
    poll();
  });
}

// Example Usage:
// async function startJobAndPoll() {
//   try {
//     const startResponse = await fetch('https://api.example.com/jobs/start', { method: 'POST' });
//     const { jobId } = await startResponse.json();
//     console.log('Job started with ID:', jobId);

//     const jobResult = await pollJobStatus(jobId, 'https://api.example.com/jobs/status');
//     console.log('Job completed, result:', jobResult);
//   } catch (error) {
//     console.error('Job process failed:', error);
//   }
// }
// startJobAndPoll();
How it works: This snippet demonstrates how to poll an API for the status of an asynchronous job. It repeatedly sends requests to a `checkUrl` with a `jobId` at a specified `interval`. The polling stops and resolves when the job status is 'completed' or rejects if it's 'failed' or times out. This pattern is crucial for long-running server processes that report progress via an API.

Need help integrating this into your project?

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

Hire DigitalCodeLabs