You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/upgrade-to-v4.mdx
+103-2
Original file line number
Diff line number
Diff line change
@@ -170,6 +170,107 @@ tasks.onComplete(({ ctx, result }) => {
170
170
});
171
171
```
172
172
173
+
### onCancel
174
+
175
+
<Note>Available in v4.0.0-beta.12 and later.</Note>
176
+
177
+
You can now define an `onCancel` hook that is called when a run is cancelled. This is useful if you want to clean up any resources that were allocated for the run.
178
+
179
+
```ts
180
+
tasks.onCancel(({ ctx, signal }) => {
181
+
console.log("Run cancelled", signal);
182
+
});
183
+
```
184
+
185
+
You can use the `onCancel` hook along with the `signal` passed into the run function to interrupt a call to an external service, for example using the [streamText](https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text) function from the AI SDK:
// We pass the signal to setTimeout to abort the timeout if the task is cancelled
251
+
awaitsetTimeout(10_000, undefined, { signal });
252
+
} catch (error) {
253
+
// Ignore the abort error
254
+
}
255
+
256
+
// Do some more work here
257
+
258
+
return {
259
+
message: "Hello, world!",
260
+
};
261
+
},
262
+
onCancel: async ({ runPromise }) => {
263
+
// You can await the runPromise to get the output of the task
264
+
const output =awaitrunPromise;
265
+
},
266
+
});
267
+
```
268
+
269
+
<Note>
270
+
You will have up to 30 seconds to complete the `runPromise` in the `onCancel` hook. After that
271
+
point the process will be killed.
272
+
</Note>
273
+
173
274
### Improved middleware and locals
174
275
175
276
Our task middleware system is now much more useful. Previously it only ran "around" the `run` function, but now we've hoisted it to the top level and it now runs before/after all the other hooks.
@@ -704,7 +805,7 @@ export const myTask = task({
704
805
id: "my-task",
705
806
onStart: ({ payload, ctx }) => {},
706
807
// The run function still uses separate parameters
0 commit comments