Run.cancel()
.cancel() 方法会取消工作流运行,停止执行并清理资源。
🌐 The .cancel() method cancels a workflow run, stopping execution and cleaning up resources.
此方法会中止任何正在运行的步骤,并将工作流状态更新为“已取消”。它适用于正在运行的工作流以及已暂停/等待的工作流。
🌐 This method aborts any running steps and updates the workflow status to 'canceled'. It works for both actively running workflows and suspended/waiting workflows.
使用示例Direct link to 使用示例
🌐 Usage example
const run = await workflow.createRun();
await run.cancel();
// Returns: { message: 'Workflow run canceled' }
参数Direct link to 参数
🌐 Parameters
No parameters:
void
This method takes no parameters
返回Direct link to 返回
🌐 Returns
result:
Promise<{ message: string }>
A promise that resolves with { message: 'Workflow run canceled' } when cancellation succeeds
取消的操作方式Direct link to 取消的操作方式
🌐 How cancellation works
当被调用时,工作流程将会:
🌐 When called, the workflow will:
- 触发中止信号 - 使用标准的 Web API AbortSignal 来通知正在运行的步骤
- 阻止后续步骤 - 不会执行任何进一步的步骤
中止信号行为Direct link to 中止信号行为
🌐 Abort signal behavior
检查 abortSignal 参数的步骤可以响应取消操作:
🌐 Steps that check the abortSignal parameter can respond to cancellation:
- 步骤可以监听 'abort' 事件:
abortSignal.addEventListener('abort', callback) - 步骤可以检查是否已中止:
if (abortSignal.aborted) { ... } - 用于取消超时、网络请求或长时间运行的操作
注意: 步骤必须主动检查中止信号才能在执行中取消。不检查信号的步骤将执行完毕,但后续步骤将不会执行。
扩展使用示例Direct link to 扩展使用示例
🌐 Extended usage examples
在出错时取消工作流Direct link to 在出错时取消工作流
🌐 Cancelling a workflow on error
const run = await workflow.createRun();
try {
const result = await run.start({ inputData: { value: "initial data" } });
} catch (error) {
await run.cancel();
}
创建一个响应取消的步骤Direct link to 创建一个响应取消的步骤
🌐 Creating a step that responds to cancellation
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 };
}
});
相关Direct link to 相关
🌐 Related