Poll until done

Wait on async work by checking back periodically until it's ready — or until you give up.

Use this to
  • Check whether a video transcoding job has finished every 2 minutes
  • Verify a POS bill has been paid 5 minutes after it was created
  • Poll an external API for export results until the file is ready to download
  • Wait for an IoT sensor to report a reading, then forward it to the dashboard
Code
Schedule the first check
await dk.schedule("check-task", {
  key: task.id,
  delay: "2m",
});
When the time comes, check and reschedule if not ready
dk.handle("check-task", async ({ key }) => {
  const task = await api.getTask(key);
  if (task.done) {
    await onTaskDone(task);
    return;
  }

  // give up after an hour — derived from the task's own state,
  // no separate counter to maintain
  const elapsedMs = Date.now() - task.createdAt.getTime();
  if (elapsedMs > 60 * 60 * 1000) {
    await alerts.page("task-stuck", { taskId: key });
    return;
  }

  // not ready yet — check again in 2 minutes
  await dk.schedule("check-task", { key, delay: "2m" });
});
npm install delaykit