0

Wait for Job

by
Published today

Poll a job until it completes and return its result. Throws if the job failed or did not complete within the timeout.

Script windmill Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 4 hours ago
1
//native
2

3
import * as wmill from "windmill-client"
4

5
// windmill-client errors only carry the status text: throw the response body, which says why
6
wmill.OpenAPI.interceptors.response.use(async (response) => {
7
  if (!response.ok) {
8
    throw new Error(`${response.status} ${await response.text()}`)
9
  }
10
  return response
11
})
12

13
/**
14
 * Wait for Job
15
 * Poll a job until it completes and return its result. Throws if the job failed or did not complete within the timeout.
16
 */
17
export async function main(
18
  id: string,
19
  timeout_secs: number = 600,
20
  poll_interval_secs: number = 2
21
) {
22
  const deadline = Date.now() + (timeout_secs || 600) * 1000
23
  while (true) {
24
    const job = await wmill.JobService.getCompletedJobResultMaybe({
25
      workspace: wmill.getWorkspace(),
26
      id,
27
    })
28
    if (job.completed) {
29
      if (!job.success) {
30
        throw new Error(`Job ${id} failed: ${JSON.stringify(job.result)}`)
31
      }
32
      return job.result
33
    }
34
    if (Date.now() > deadline) {
35
      throw new Error(`Job ${id} did not complete within ${timeout_secs}s`)
36
    }
37
    await new Promise((r) => setTimeout(r, (poll_interval_secs || 2) * 1000))
38
  }
39
}
40