0
# Task Management
1
2
Core task execution and lifecycle management functionality for creating, running, and controlling asynchronous operations in Lit elements.
3
4
## Capabilities
5
6
### Task Class
7
8
The main Task class that serves as a reactive controller for managing asynchronous operations.
9
10
```typescript { .api }
11
/**
12
* A controller that performs an asynchronous task when its host element updates.
13
* Requests updates on the host element when the task starts and completes.
14
*/
15
class Task<T extends ReadonlyArray<unknown>, R> {
16
/** Controls automatic task execution */
17
autoRun: boolean | 'afterUpdate';
18
19
/** Result of the previous task run, if it resolved */
20
readonly value?: R;
21
22
/** Error from the previous task run, if it rejected */
23
readonly error?: unknown;
24
25
/** Current task status */
26
readonly status: TaskStatus;
27
28
/**
29
* Promise that resolves when the current task run is complete
30
* - If task is PENDING: Promise resolves when task completes
31
* - If task is COMPLETE: Promise resolves immediately with current value
32
* - If task is ERROR: Promise rejects immediately with current error
33
* - If task is INITIAL: Promise resolves immediately with undefined
34
*/
35
readonly taskComplete: Promise<R>;
36
}
37
```
38
39
### Task Constructors
40
41
Two constructor overloads for creating Task instances.
42
43
```typescript { .api }
44
/**
45
* Create a Task with a configuration object
46
* @param host - Lit element that owns this task
47
* @param config - Task configuration object
48
*/
49
constructor(host: ReactiveControllerHost, config: TaskConfig<T, R>);
50
51
/**
52
* Create a Task with individual parameters
53
* @param host - Lit element that owns this task
54
* @param task - The task function to execute
55
* @param args - Function that returns task arguments
56
*/
57
constructor(
58
host: ReactiveControllerHost,
59
task: TaskFunction<T, R>,
60
args?: ArgsFunction<T>
61
);
62
```
63
64
**Usage Examples:**
65
66
```typescript
67
import { LitElement } from "lit";
68
import { Task } from "@lit/task";
69
70
class MyElement extends LitElement {
71
// Using configuration object
72
task1 = new Task(this, {
73
task: async ([id]) => {
74
const response = await fetch(`/api/data/${id}`);
75
return response.json();
76
},
77
args: () => [this.dataId],
78
autoRun: true,
79
onComplete: (result) => console.log('Task completed:', result),
80
onError: (error) => console.error('Task failed:', error)
81
});
82
83
// Using individual parameters
84
task2 = new Task(
85
this,
86
async ([query]) => searchAPI(query),
87
() => [this.searchQuery]
88
);
89
}
90
```
91
92
### Task Configuration
93
94
Configuration object for advanced task setup.
95
96
```typescript { .api }
97
interface TaskConfig<T extends ReadonlyArray<unknown>, R> {
98
/** The task function to execute */
99
task: TaskFunction<T, R>;
100
101
/** Function that returns task arguments */
102
args?: ArgsFunction<T>;
103
104
/**
105
* Controls automatic task execution
106
* - true: Run during host update (default)
107
* - 'afterUpdate': Run after host update
108
* - false: Manual execution only
109
*/
110
autoRun?: boolean | 'afterUpdate';
111
112
/** Function to compare argument arrays for equality */
113
argsEqual?: (oldArgs: T, newArgs: T) => boolean;
114
115
/** Initial value to set task as completed */
116
initialValue?: R;
117
118
/** Callback when task completes successfully */
119
onComplete?: (value: R) => unknown;
120
121
/** Callback when task fails with error */
122
onError?: (error: unknown) => unknown;
123
}
124
```
125
126
### Task Execution
127
128
Methods for controlling task execution.
129
130
```typescript { .api }
131
/**
132
* Manually run the task with optional custom arguments
133
* @param args - Optional arguments to use for this run
134
* @returns Promise that resolves when task completes
135
*/
136
async run(args?: T): Promise<void>;
137
138
/**
139
* Abort the currently pending task run
140
* @param reason - Optional reason for aborting
141
*/
142
abort(reason?: unknown): void;
143
```
144
145
### Lifecycle Methods
146
147
Methods that integrate with the host element's update cycle as part of the reactive controller pattern.
148
149
```typescript { .api }
150
/**
151
* Called during host element update phase
152
* Triggers automatic task execution if autoRun is true
153
*/
154
hostUpdate(): void;
155
156
/**
157
* Called after host element update phase
158
* Triggers automatic task execution if autoRun is 'afterUpdate'
159
*/
160
hostUpdated(): void;
161
```
162
163
**Note:** These methods are called automatically by Lit's reactive controller system. You typically don't need to call them manually.
164
165
**Usage Examples:**
166
167
```typescript
168
// Manual task execution
169
await myTask.run();
170
171
// Run with custom arguments
172
await myTask.run(['custom', 'arguments']);
173
174
// Abort pending task
175
myTask.abort('User cancelled');
176
177
// Wait for task completion
178
try {
179
const result = await myTask.taskComplete;
180
console.log('Task result:', result);
181
} catch (error) {
182
console.error('Task failed:', error);
183
}
184
185
// Combining run and taskComplete
186
await myTask.run();
187
const result = await myTask.taskComplete;
188
```
189
190
### Task Functions
191
192
Function signatures for task implementation.
193
194
```typescript { .api }
195
/**
196
* Function that performs the actual task work
197
* @param args - Arguments array from args function
198
* @param options - Task execution options including AbortSignal
199
* @returns Task result, Promise of result, or initialState symbol
200
*/
201
type TaskFunction<D extends ReadonlyArray<unknown>, R = unknown> = (
202
args: D,
203
options: TaskFunctionOptions
204
) => R | typeof initialState | Promise<R | typeof initialState>;
205
206
/**
207
* Function that returns arguments for task execution
208
* @returns Array of arguments to pass to task function
209
*/
210
type ArgsFunction<D extends ReadonlyArray<unknown>> = () => D;
211
212
/**
213
* Legacy alias for ArgsFunction (maintained for backward compatibility)
214
*/
215
type DepsFunction<D extends ReadonlyArray<unknown>> = ArgsFunction<D>;
216
217
/**
218
* Options passed to task functions
219
*/
220
interface TaskFunctionOptions {
221
/** AbortSignal for cancelling the task */
222
signal: AbortSignal;
223
}
224
```
225
226
### Initial State Control
227
228
Special symbol for resetting task state.
229
230
```typescript { .api }
231
/**
232
* Special value that can be returned from task functions to reset the task
233
* status to INITIAL state
234
*/
235
const initialState: unique symbol;
236
```
237
238
**Usage Example:**
239
240
```typescript
241
const conditionalTask = new Task(this, {
242
task: async ([shouldRun]) => {
243
if (!shouldRun) {
244
return initialState; // Reset to INITIAL state
245
}
246
return await performWork();
247
},
248
args: () => [this.shouldRunTask]
249
});
250
```