> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # Run.cancel() `.cancel()` 方法會取消 Workflow 執行,停止執行流程並清理資源。 此方法會中止任何正在執行的步驟,並將 Workflow 狀態更新為 'canceled'。它同時適用於正在執行以及已暫停/等待中的 Workflow。 ## 使用範例 ```typescript const run = await workflow.createRun() await run.cancel() // Returns: { message: 'Workflow run canceled' } ``` ## 參數 **沒有參數** (`void`): 此方法不接受任何參數 ## 傳回值 **result** (`Promise<{ message: string }>`): 取消成功時,會解析為 { message: 'Workflow run canceled' } 的 Promise ## 取消機制 呼叫此方法時,Workflow 將會: 1. **觸發中止訊號** - 使用標準 Web API AbortSignal 通知正在執行的步驟 2. **阻止後續步驟** - 不會再執行任何後續步驟 ## 中止訊號的行為 檢查 `abortSignal` 參數的步驟可以回應取消操作: - 步驟可以監聽 'abort' 事件:`abortSignal.addEventListener('abort', callback)` - 步驟可以檢查是否已中止:`if (abortSignal.aborted) { ... }` - 適合用來取消逾時、網絡請求或長時間執行的操作 步驟必須主動檢查中止訊號,才能在執行途中取消;否則目前步驟會執行至完成,而後續步驟則不會執行。 ## 延伸使用範例 ### 發生錯誤時取消 Workflow ```typescript const run = await workflow.createRun() try { const result = await run.start({ inputData: { value: 'initial data' } }) } catch (error) { await run.cancel() } ``` ### 建立可回應取消操作的步驟 ```typescript const step = createStep({ id: 'long-running-step', execute: async ({ inputData, abortSignal, abort }) => { const timeout = new Promise(resolve => { const timer = setTimeout(() => resolve('done'), 10000) // Clean up if canceled abortSignal.addEventListener('abort', () => { clearTimeout(timer) resolve('canceled') }) }) const result = await timeout // Check if aborted after async operation if (abortSignal.aborted) { return abort() // Stop execution } return { result } }, }) ``` ## 相關內容 - [Workflows 概覽](https://mastra.zisheng.pro/zh-HK/docs/workflows/overview) - [Workflow.createRun()](https://mastra.zisheng.pro/zh-HK/reference/workflows/workflow-methods/create-run)