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

# 异步任务查询 API

> 查询异步任务的处理结果，获取最终的处理结果

export const baseUrl = 'https://api.aihairstyle.cn';

## 请求

* **URL**: {baseUrl}/common/query-async-task-result
* **方法**: `POST`

### 请求头

| 字段                 | 必填 | 类型       | 描述                                               |
| :----------------- | :- | :------- | :----------------------------------------------- |
| `ailabapi-api-key` | 是  | `string` | 应用 API KEY。 [获取 API KEY](/common/authentication) |

### 请求体参数

#### 固定字段

| 字段        | 必填 | 类型       | 描述                  |
| :-------- | :- | :------- | :------------------ |
| `task_id` | 是  | `string` | 异步 API 返回的 task\_id |

# 异步任务查询 API

查询异步任务的处理结果，获取最终的处理结果。对于异步接口，在调用 API 后返回的结果不是真实的请求结果，您需要保存返回结果中的 `task_id`，然后调用此接口获取真实的请求结果。

## 功能特点

* **任务状态查询**：实时查询异步任务的处理状态
* **结果获取**：获取任务完成后的最终结果
* **状态监控**：监控任务从排队到完成的整个过程
* **错误处理**：处理任务失败的情况

## 应用场景

* **异步处理**：配合异步 API 使用，获取处理结果
* **状态监控**：实时监控任务处理进度
* **结果获取**：获取发型编辑、人脸分析等任务的最终结果
* **错误恢复**：处理任务失败后的重试逻辑

## 任务状态说明

| 状态码  | 状态  | 说明            |
| ---- | --- | ------------- |
| `0`  | 排队中 | 任务已提交，正在等待处理  |
| `1`  | 处理中 | 任务正在处理中       |
| `2`  | 已完成 | 任务处理成功，可以获取结果 |
| `-1` | 失败  | 任务处理失败        |

## 响应示例

### 任务排队中

```json theme={null}
{
  "request_id": "123456789",
  "log_id": "987654321",
  "error_code": 0,
  "error_msg": "",
  "error_detail": {
    "status_code": 200,
    "code": "",
    "code_message": "",
    "message": ""
  },
  "task_status": 0
}
```

### 任务处理中

```json theme={null}
{
  "request_id": "123456789",
  "log_id": "987654321",
  "error_code": 0,
  "error_msg": "",
  "error_detail": {
    "status_code": 200,
    "code": "",
    "code_message": "",
    "message": ""
  },
  "task_status": 1
}
```

### 任务已完成

```json theme={null}
{
  "request_id": "123456789",
  "log_id": "987654321",
  "error_code": 0,
  "error_msg": "",
  "error_detail": {
    "status_code": 200,
    "code": "",
    "code_message": "",
    "message": ""
  },
  "task_status": 2,
  "result": [
    "https://example.com/result1.jpg",
    "https://example.com/result2.jpg",
    "https://example.com/result3.jpg",
    "https://example.com/result4.jpg"
  ]
}
```

### 任务失败

```json theme={null}
{
  "request_id": "123456789",
  "log_id": "987654321",
  "error_code": 0,
  "error_msg": "",
  "error_detail": {
    "status_code": 200,
    "code": "",
    "code_message": "",
    "message": ""
  },
  "task_status": -1
}
```

### 错误响应

```json theme={null}
{
  "request_id": "123456789",
  "log_id": "987654321",
  "error_code": 400,
  "error_msg": "Invalid task_id",
  "error_detail": {
    "status_code": 400,
    "code": "ERROR_INVALID_TASK_ID",
    "code_message": "Invalid task ID",
    "message": "The provided task_id is invalid or expired"
  }
}
```

## 响应字段说明

| 字段            | 类型      | 说明                            |
| ------------- | ------- | ----------------------------- |
| `task_status` | integer | 任务状态：0=排队中，1=处理中，2=已完成，-1=失败  |
| `result`      | array   | 任务结果数组（仅在 task\_status=2 时返回） |

## 最佳实践

### 1. 轮询查询

```javascript theme={null}
async function pollAsyncTask(taskId, maxAttempts = 100) {
  const interval = 5000; // 5秒间隔
  
  for (let i = 0; i < maxAttempts; i++) {
    try {
      const result = await queryAsyncTask(taskId);
      
      switch (result.task_status) {
        case 0:
          console.log('任务排队中...');
          break;
        case 1:
          console.log('任务处理中...');
          break;
        case 2:
          console.log('任务完成！');
          return result;
        case -1:
          throw new Error('任务处理失败');
        default:
          throw new Error('未知的任务状态');
      }
      
      // 等待后重试
      await new Promise(resolve => setTimeout(resolve, interval));
      
    } catch (error) {
      console.error('查询任务状态失败:', error);
      if (i === maxAttempts - 1) {
        throw error;
      }
    }
  }
  
  throw new Error('任务超时');
}
```

### 2. 带进度显示的查询

```javascript theme={null}
async function pollWithProgress(taskId, onProgress) {
  const maxAttempts = 100;
  const interval = 5000;
  
  for (let i = 0; i < maxAttempts; i++) {
    const result = await queryAsyncTask(taskId);
    
    // 计算进度
    let progress = 0;
    switch (result.task_status) {
      case 0:
        progress = 10;
        break;
      case 1:
        progress = 50 + (i / maxAttempts) * 40; // 50%-90%
        break;
      case 2:
        progress = 100;
        break;
      case -1:
        throw new Error('任务处理失败');
    }
    
    // 回调进度
    onProgress(progress, result.task_status);
    
    if (result.task_status === 2) {
      return result;
    }
    
    await new Promise(resolve => setTimeout(resolve, interval));
  }
  
  throw new Error('任务超时');
}

// 使用示例
pollWithProgress('task_123456789', (progress, status) => {
  console.log(`进度: ${progress}%, 状态: ${status}`);
});
```

### 3. 错误处理和重试

```javascript theme={null}
async function queryWithRetry(taskId, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const result = await queryAsyncTask(taskId);
      
      if (result.task_status === -1) {
        throw new Error('任务处理失败');
      }
      
      return result;
      
    } catch (error) {
      console.error(`第 ${i + 1} 次查询失败:`, error);
      
      if (i === maxRetries - 1) {
        throw error;
      }
      
      // 指数退避
      const delay = Math.pow(2, i) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}
```

## 注意事项

<Warning>
  * 异步任务结果有效期为 24 小时
  * 建议每 5 秒查询一次结果
  * 任务失败后无法重试，需要重新提交任务
  * 请妥善保存 task\_id，避免丢失
</Warning>

<Tip>
  **优化建议**：

  * 使用 WebSocket 或 Server-Sent Events 获取实时状态更新
  * 实现指数退避算法避免频繁请求
  * 添加超时机制防止无限等待
  * 缓存查询结果减少重复请求
</Tip>

## 相关链接

* [发型编辑 Pro API](/api-reference/hairstyle-editor-pro)
* [人脸分析 API](/api-reference/face-analysis)
* [错误处理](/essentials/error-handling)


## OpenAPI

````yaml GET /common/query-async-task-result
openapi: 3.0.0
info:
  title: AI发型设计 API
  description: AI发型设计 提供简单灵活的 API 端点，满足您的 AI 需求
  version: 1.0.0
  contact:
    name: AI发型设计 Support
servers:
  - url: https://api.aihairstyle.cn
    description: Production server
security: []
paths:
  /common/query-async-task-result:
    get:
      tags:
        - Common
      summary: Query Async Task Results
      description: 查询异步任务的处理结果，获取最终的处理结果
      parameters:
        - name: task_id
          in: query
          required: true
          schema:
            type: string
          description: The task_id returned by the asynchronous API.
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AsyncTaskResponse'
        '400':
          description: Bad Request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SuccessResponse'
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SuccessResponse'
      security:
        - apiKeyAuth: []
components:
  schemas:
    AsyncTaskResponse:
      allOf:
        - $ref: '#/components/schemas/SuccessResponse'
        - type: object
          properties:
            task_status:
              type: integer
              description: 'Task status: 0=queued, 1=processing, 2=completed, -1=failed'
              enum:
                - 0
                - 1
                - 2
                - -1
            result:
              type: array
              items:
                type: string
                description: Result image URL
              description: Array of result image URLs (when task_status=2)
    SuccessResponse:
      type: object
      properties:
        request_id:
          type: string
          description: Request ID
        log_id:
          type: string
          description: Log ID
        error_code:
          type: integer
          description: Status code (0 for success)
        error_msg:
          type: string
          description: Error message
        error_detail:
          type: object
          properties:
            status_code:
              type: integer
              description: HTTP status code
            code:
              type: string
              description: Error code
            code_message:
              type: string
              description: Error code description
            message:
              type: string
              description: Detailed error message
  securitySchemes:
    apiKeyAuth:
      type: apiKey
      in: header
      name: ailabapi-api-key
      description: API Key for authentication

````