0
# Event System
1
2
Comprehensive event system for monitoring job lifecycle, handling errors, and responding to timeouts. The Queue extends EventTarget and uses custom QueueEvent instances.
3
4
## Capabilities
5
6
### QueueEvent Class
7
8
Custom event class that carries detailed information about queue operations.
9
10
```javascript { .api }
11
/**
12
* Custom event class for queue events with detail payload
13
*/
14
class QueueEvent extends Event {
15
constructor(name: string, detail: any);
16
/** Event-specific data payload */
17
readonly detail: any;
18
}
19
```
20
21
### Event Listeners
22
23
Standard EventTarget methods for managing event listeners.
24
25
```javascript { .api }
26
/**
27
* Add event listener for queue events
28
* @param name - Event name to listen for
29
* @param callback - Event handler function
30
* @param options - Optional listener options
31
*/
32
addEventListener<Event extends keyof EventsMap>(
33
name: Event,
34
callback: EventListenerOrEventListenerObject<QueueEvent<Event, EventsMap[Event]>>,
35
options?: AddEventListenerOptions | boolean
36
): void;
37
38
/**
39
* Remove event listener
40
* @param name - Event name to stop listening for
41
* @param callback - Event handler function to remove
42
* @param options - Optional listener options
43
*/
44
removeEventListener<Event extends keyof EventsMap>(
45
name: Event,
46
callback: EventListenerOrEventListenerObject<QueueEvent<Event, EventsMap[Event]>>,
47
options?: EventListenerOptions | boolean
48
): void;
49
50
/**
51
* Dispatch custom queue events
52
* @param event - QueueEvent to dispatch
53
* @returns Whether the event was handled
54
*/
55
dispatchEvent<Event extends keyof EventsMap>(event: QueueEvent<Event, EventsMap[Event]>): boolean;
56
57
/**
58
* Event listener callback type
59
*/
60
type EventListenerOrEventListenerObject<Event extends QueueEvent<keyof EventsMap, EventsMap[keyof EventsMap]>> =
61
(event: Event) => void | { handleEvent(Event: Event): void; };
62
```
63
64
### Event Types
65
66
#### Start Event
67
68
Fired immediately before a job begins execution.
69
70
```javascript { .api }
71
// Event detail structure
72
interface StartEventDetail {
73
job?: QueueWorker; // Optional in TypeScript definitions
74
}
75
```
76
77
**Usage Example:**
78
79
```javascript
80
q.addEventListener('start', (event) => {
81
if (event.detail.job) {
82
console.log('Job starting:', event.detail.job.name);
83
}
84
});
85
```
86
87
#### Success Event
88
89
Fired after a job successfully completes execution.
90
91
```javascript { .api }
92
// Event detail structure
93
interface SuccessEventDetail {
94
result: any[]; // Job return values array
95
}
96
```
97
98
**Usage Example:**
99
100
```javascript
101
q.addEventListener('success', (event) => {
102
const { result } = event.detail;
103
console.log('Job completed successfully:', result);
104
});
105
```
106
107
#### Error Event
108
109
Fired when a job calls its callback with an error or throws an exception.
110
111
```javascript { .api }
112
// Event detail structure
113
interface ErrorEventDetail {
114
error: Error; // The error that occurred
115
job: QueueWorker; // The job that failed
116
}
117
```
118
119
**Usage Example:**
120
121
```javascript
122
q.addEventListener('error', (event) => {
123
const { error, job } = event.detail;
124
console.error('Job failed:', job.name, error.message);
125
126
// Log error details
127
logger.error({
128
jobName: job.name,
129
error: error.message,
130
stack: error.stack
131
});
132
});
133
```
134
135
#### Timeout Event
136
137
Fired when a job exceeds its timeout duration without completing.
138
139
```javascript { .api }
140
// Event detail structure
141
interface TimeoutEventDetail {
142
next: (error?: Error, ...result: any[]) => void; // Callback to continue
143
job: QueueWorker; // The job that timed out
144
}
145
```
146
147
**Usage Example:**
148
149
```javascript
150
q.addEventListener('timeout', (event) => {
151
const { next, job } = event.detail;
152
153
console.log('Job timed out:', job.toString().replace(/\n/g, ''));
154
155
// Cancel the job and continue processing
156
next(new Error('Job timed out'));
157
158
// Or allow job to continue (job might still complete)
159
// next();
160
});
161
```
162
163
#### End Event
164
165
Fired when the queue finishes processing all jobs, either successfully or due to an error.
166
167
```javascript { .api }
168
// Event detail structure
169
interface EndEventDetail {
170
error?: Error; // Error if queue ended due to failure
171
}
172
```
173
174
**Usage Example:**
175
176
```javascript
177
q.addEventListener('end', (event) => {
178
const { error } = event.detail;
179
180
if (error) {
181
console.error('Queue ended with error:', error.message);
182
} else {
183
console.log('Queue completed successfully');
184
}
185
186
// Cleanup resources
187
cleanup();
188
});
189
```
190
191
### Complete Event Handling Example
192
193
```javascript
194
import Queue from "queue";
195
196
const q = new Queue({
197
concurrency: 2,
198
timeout: 5000,
199
results: []
200
});
201
202
// Monitor job lifecycle
203
q.addEventListener('start', (event) => {
204
console.log(`Starting job: ${event.detail.job.name || 'anonymous'}`);
205
});
206
207
q.addEventListener('success', (event) => {
208
console.log(`Job completed: ${event.detail.result}`);
209
});
210
211
q.addEventListener('error', (event) => {
212
console.error(`Job failed: ${event.detail.error.message}`);
213
});
214
215
q.addEventListener('timeout', (event) => {
216
console.warn('Job timed out, cancelling...');
217
event.detail.next(new Error('Timeout'));
218
});
219
220
q.addEventListener('end', (event) => {
221
if (event.detail.error) {
222
console.error('Queue failed:', event.detail.error.message);
223
} else {
224
console.log('All jobs completed successfully');
225
console.log('Results:', q.results);
226
}
227
});
228
229
// Add some jobs
230
q.push(
231
function fastJob(callback) {
232
setTimeout(() => callback(null, 'fast'), 100);
233
},
234
235
function slowJob(callback) {
236
setTimeout(() => callback(null, 'slow'), 10000); // Will timeout
237
},
238
239
function errorJob(callback) {
240
callback(new Error('Something went wrong'));
241
}
242
);
243
244
// Start processing
245
q.start();
246
```
247
248
## Event Types Map
249
250
```javascript { .api }
251
/**
252
* Complete mapping of event names to their detail types
253
*/
254
interface EventsMap {
255
start: { job?: QueueWorker };
256
success: { result: any[] };
257
error: { error: Error, job: QueueWorker };
258
timeout: { next: (err?: Error, ...result: any[]) => void, job: QueueWorker };
259
end: { error?: Error };
260
}
261
```