ARTICLE AD BOX
I am polling an async video generation job from a Node.js backend.
The API I am testing is a Flaq AI text-to-video endpoint for a Happy Horse 1.0 model, but the issue is not specific to that API. It is about how to wait between polling attempts in JavaScript.
The API flow is:
1. I create a job.
2. The API returns a job id.
3. I call a status endpoint until the job status is either succeeded or failed.
4. If the job succeeds, I return the video URL.
In my real code, the job can take longer than a few seconds. However, my polling loop appears to run all attempts almost immediately, and the function returns undefined before the job has time to finish.
Here is the smallest version of the problem:
async function getJobStatus(jobId) { // This represents a real fetch call to a status endpoint. return { status: "processing", output: null }; } async function waitForVideo(jobId) { for (let i = 0; i \< 10; i++) { const job = await getJobStatus(jobId); if (job.status === "succeeded") { return job.output.video_url; } if (job.status === "failed") { throw new Error("Video generation failed"); } setTimeout(() =\> {}, 3000); } } async function main() { const videoUrl = await waitForVideo("job_123"); console.log(videoUrl); } main();The line I expected to pause the loop is this:
setTimeout(() =\> {}, 3000);My understanding now is that this schedules a timer, but it does not make the async function wait.
What is the correct way to pause between polling attempts?
Should I write a helper like this?
function sleep(ms) { return new Promise(resolve =\> setTimeout(resolve, ms)); }And then use:
await sleep(3000);Also, when the loop reaches the maximum number of attempts, should I explicitly throw a timeout error instead of letting the function return undefined?
