Async Tasks
Understanding the asynchronous task pattern
Several DataTalk API operations are long-running — they involve AI processing. These operations use an async task pattern instead of blocking the request.
How It Works
- You call an endpoint (e.g.,
POST /generate-query) - The API returns immediately with a
taskIdand status202 Accepted - You poll
GET /task/:taskIduntil the task completes - Alternatively, configure webhooks to receive push notifications when tasks complete
Endpoints That Create Tasks
| Endpoint | Task Type |
|---|---|
POST /generate-query | GENERATE_QUERY |
Task Lifecycle
PENDING → PROCESSING → COMPLETED
→ FAILED| Status | Description |
|---|---|
PENDING | Task is queued and waiting to be picked up |
PROCESSING | Task is actively being processed by the AI |
COMPLETED | Task finished successfully — check the result field |
FAILED | Task failed — check the error field |
Polling Strategy
The GET /task/:taskId endpoint returns a Retry-After: 2 header when the task is not yet complete. A recommended polling approach:
async function pollTask(taskId) {
while (true) {
const res = await fetch(`${API_BASE}/task/${taskId}`, {
headers: { Authorization: `Bearer ${API_KEY}` },
});
const task = await res.json();
if (task.status === "COMPLETED" || task.status === "FAILED") {
if (task.status === "FAILED") {
throw new Error(JSON.stringify(task.error));
}
return task;
}
// Respect the Retry-After header
const retryAfter = res.headers.get("Retry-After") ?? "2";
await new Promise((r) => setTimeout(r, parseInt(retryAfter) * 1000));
}
}Token Usage
Completed tasks include a usage object with AI token consumption:
{
"usage": {
"inputTokens": 1250,
"outputTokens": 85,
"totalTokens": 1335,
"costUsd": 0.0042
}
}This lets you track AI costs per request.
Webhooks as Alternative
Instead of polling, you can receive push notifications by configuring webhook endpoints in your user settings. See Webhooks for details.