JAVASCRIPT
Implement API Polling for Asynchronous Task Status Updates
Discover how to poll a backend API endpoint periodically to check the status of a long-running asynchronous task until it completes or fails, ensuring real-time feedback.
async function pollTaskStatus(taskId, intervalMs = 2000, maxAttempts = 30) {
let attempts = 0;
return new Promise((resolve, reject) => {
const poller = setInterval(async () => {
attempts++;
if (attempts > maxAttempts) {
clearInterval(poller);
return reject(new Error('Max polling attempts reached. Task timed out.'));
}
try {
const response = await fetch(`/api/tasks/${taskId}/status`);
if (!response.ok) {
throw new Error(`Failed to fetch task status: ${response.status} ${response.statusText}`);
}
const statusData = await response.json();
// Assuming the API returns a 'status' field, e.g., 'PENDING', 'COMPLETED', 'FAILED'
if (statusData.status === 'COMPLETED') {
clearInterval(poller);
resolve(statusData); // Resolve with the final task data
} else if (statusData.status === 'FAILED') {
clearInterval(poller);
reject(new Error(`Task failed: ${statusData.errorMessage || 'Unknown error'}`));
} else {
console.log(`Task ${taskId} is still ${statusData.status}. Attempt ${attempts}/${maxAttempts}...`);
}
} catch (error) {
clearInterval(poller);
reject(new Error(`Polling error for task ${taskId}: ${error.message}`));
}
}, intervalMs);
});
}
// Example Usage:
// Assume we initiated a long-running task and got a taskId back.
// const myTaskId = 'abc-123-def';
// pollTaskStatus(myTaskId, 3000, 20) // Poll every 3 seconds, max 20 attempts
// .then(result => console.log('Task completed successfully:', result))
// .catch(error => console.error('Task polling failed:', error));
How it works: This JavaScript snippet demonstrates how to implement API polling to monitor the status of an asynchronous backend task. It uses `setInterval` to repeatedly send `fetch` requests to a status endpoint at a specified interval. The polling continues until the task status indicates 'COMPLETED' or 'FAILED', or until a maximum number of attempts is reached, preventing infinite loops. This pattern is essential for providing user feedback on long-running operations where immediate responses are not possible.