> ## 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-hant/api-reference/generate-task.md)、[狀態檢查](https://apixo.ai/docs/zh-hant/api-reference/status-task.md)和結果檢索來執行單一任務。如果您已經了解任務生命週期，[比較輪詢和 Webhooks](https://apixo.ai/docs/zh-hant/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-hant/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-hant/models.md)
>
> 瞭解影像、影片和音訊模型的非同步 API 模式

> [card] [生成任務](https://apixo.ai/docs/zh-hant/api-reference/generate-task.md)
>
> 送出生成任務並接收任務ID

> [card] [輪詢與 Webhook](https://apixo.ai/docs/zh-hant/guides/polling-vs-webhooks.md)
>
> 深入研究這兩種方法


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