> ## Documentation Index
> Fetch the complete documentation index at: https://apixo.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 异步任务：从提交、轮询到获取结果

> 了解 APIXO 的异步任务模式：提交生成任务、轮询其状态或使用 Webhook，并获取结果 URL。

异步生成请求在输出准备好前返回任务 ID。请将 **模型 ID 和任务 ID 一起保存**。重启后检查进度时使用同一对；再次提交提示将启动新的作业。

通过下面的[提交](https://apixo.ai/docs/zh/api-reference/generate-task.md)、[状态检查](https://apixo.ai/docs/zh/api-reference/status-task.md)和结果检索来执行单个任务。如果您已经了解任务生命周期，[比较轮询和 Webhooks](https://apixo.ai/docs/zh/guides/polling-vs-webhooks.md) 以选择交付方法。

## 模式

```
┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│   Submit    │────▶│  Poll or    │────▶│   Retrieve  │
│   Task      │     │  Callback   │     │   Results   │
└─────────────┘     └─────────────┘     └─────────────┘
      │                   │                   │
      ▼                   ▼                   ▼
   taskId            state check          resultUrls
```

## 步骤 1：提交任务

发送`POST`请求创建生成任务：

```bash theme={null}
POST https://api.apixo.ai/api/v1/generateTask/{model}
```

**请求：**

```json theme={null}
{
  "request_type": "async",
  "input": {
    "mode": "text-to-image",
    "prompt": "A beautiful sunset over mountains"
  }
}
```

**响应：**

```json theme={null}
{
  "code": 200,
  "message": "success",
  "data": {
    "taskId": "task_abc123xyz"
  }
}
```

API立即返回`taskId`。实际的生成发生在后台。

## 步骤 2：获取结果

您有两种接收结果的选择：

### 选项 A：轮询（建议入门）

定期检查任务状态：

```bash theme={null}
GET https://api.apixo.ai/api/v1/statusTask/{model}?taskId={taskId}
```

**响应（正在进行中）：**

```json theme={null}
{
  "data": {
    "taskId": "task_abc123xyz",
    "state": "processing"
  }
}
```

**响应（已完成）：**

```json theme={null}
{
  "data": {
    "taskId": "task_abc123xyz",
    "state": "success",
    "resultJson": "{\"resultUrls\":[\"https://cdn.apixo.ai/...\"]}",
    "costTime": 12500
  }
}
```

### 选项 B：Webhooks（推荐用于生产）

提交时提供 `callback_url`：

```json theme={null}
{
  "request_type": "callback",
  "callback_url": "https://your-server.com/webhook/apixo",
  "input": { ... }
}
```

任务完成后，APIXO 会将结果 `POST` 发送给您的 URL。

请参阅 [Webhooks](https://apixo.ai/docs/zh/api-reference/webhooks.md) 了解实现细节。

## 任务状态

| 状态 | 说明 |
| - | - |
| `pending` | 任务已排队，等待开始 |
| `processing` | 任务正在处理中 |
| `success` | 任务成功完成 |
| `failed` | 任务失败（检查 `failMsg`） |

## 轮询最佳实践

1. **对于大多数任务，以 3-5 秒间隔开始**
2. **对长时间运行的任务使用指数退避**（视频）
3. **设置最大超时**（例如，5 分钟）
4. **通过重试逻辑优雅地处理故障**

```javascript theme={null}
const pollWithBackoff = async (taskId, maxWait = 300000) => {
  let interval = 3000; // Start at 3s
  const startTime = Date.now();
  
  while (Date.now() - startTime < maxWait) {
    const result = await checkStatus(taskId);
    
    if (result.state === 'success') return result;
    if (result.state === 'failed') throw new Error(result.failMsg);
    
    await sleep(interval);
    interval = Math.min(interval * 1.5, 30000); // Max 30s
  }
  
  throw new Error('Timeout waiting for result');
};
```

## 何时使用每种方法

| 方法 | 最适合 |
| - | - |
| **轮询** | 简单的集成、客户端应用程序、测试 |
| **Webhook** | 生产服务器、实时应用程序、大容量 |

## 下一步

> [card] [生成 API概述](https://apixo.ai/docs/zh/models.md)
>
> 了解图像、视频和音频模型的异步 API 模式

> [card] [生成任务](https://apixo.ai/docs/zh/api-reference/generate-task.md)
>
> 提交生成任务并接收任务ID

> [card] [轮询与 Webhook](https://apixo.ai/docs/zh/guides/polling-vs-webhooks.md)
>
> 深入研究这两种方法


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.