0
# Q Promise Library
1
2
Q is a comprehensive promise library for JavaScript that implements the CommonJS Promises/A, B, and D specifications. It provides a robust foundation for asynchronous programming with features including promise chaining, error propagation, progress notifications, and utilities for combining multiple promises. Q supports both Node.js and browser environments, provides long stack trace support for debugging, and includes adapter functions for converting Node.js callback-style functions to promise-based ones.
3
4
## Package Information
5
6
- **Package Name**: q
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install q`
10
11
## Core Imports
12
13
```javascript
14
const Q = require("q");
15
```
16
17
ESM (if using transpiler):
18
19
```javascript
20
import Q from "q";
21
```
22
23
For specific functions (all are properties of Q):
24
25
```javascript
26
const Q = require("q");
27
const { defer, delay, all, race } = Q;
28
```
29
30
## Basic Usage
31
32
```javascript
33
const Q = require("q");
34
35
// Create a promise from a value
36
const promise = Q("Hello World");
37
38
// Create a deferred
39
const deferred = Q.defer();
40
setTimeout(() => {
41
deferred.resolve("Delayed result");
42
}, 1000);
43
44
// Chain promises
45
promise
46
.then(value => value.toUpperCase())
47
.then(value => console.log(value))
48
.catch(error => console.error(error))
49
.done();
50
51
// Convert Node.js callback to promise
52
const fs = require("fs");
53
const readFile = Q.denodeify(fs.readFile);
54
readFile("package.json", "utf8")
55
.then(data => JSON.parse(data))
56
.then(json => console.log(json.name))
57
.catch(console.error);
58
```
59
60
## Architecture
61
62
Q is built around several key components:
63
64
- **Core Promise Creation**: Main Q function, defer, reject, Promise constructor for creating promises
65
- **State Management**: Promise state inspection (pending, fulfilled, rejected) and introspection
66
- **Collection Operations**: Processing arrays of promises with all, allSettled, spread operations
67
- **Flow Control**: Timing control with delay, timeout, race, and conditional processing
68
- **Functional Utilities**: Function wrapping, async/generator support, and promise-based functional programming
69
- **Node.js Integration**: Seamless callback-to-promise conversion with denodeify and ninvoke methods
70
- **Error Handling**: Comprehensive error propagation, long stack traces, and global error handling
71
- **Advanced Features**: Pass-by-copy semantics, timing estimates, and low-level dispatch operations
72
73
## Capabilities
74
75
### Core Promise Creation
76
77
Essential functions for creating and managing promises from values, errors, and callback functions.
78
79
```javascript { .api }
80
// Main promise creation function
81
function Q(value);
82
83
// Create deferred objects
84
function Q.defer();
85
86
// Create rejected promises
87
function Q.reject(error);
88
89
// Promise constructor
90
function Q.Promise(resolver);
91
92
// Try function execution
93
function Q.try(callback);
94
```
95
96
[Core Promise Creation](./core-promises.md)
97
98
### Promise State and Inspection
99
100
Methods for examining promise state and extracting information about promise fulfillment status.
101
102
```javascript { .api }
103
// Test promise type
104
function Q.isPromise(object);
105
106
// Instance state inspection methods
107
promise.inspect();
108
promise.isPending();
109
promise.isFulfilled();
110
promise.isRejected();
111
```
112
113
[State Inspection](./state-inspection.md)
114
115
### Collection and Array Operations
116
117
Functions for working with arrays of promises, combining multiple asynchronous operations.
118
119
```javascript { .api }
120
// Process arrays of promises
121
function Q.all(promises);
122
function Q.allSettled(promises);
123
function Q.spread(promise, fulfilled, rejected);
124
function Q.race(promises);
125
126
// Instance collection methods
127
promise.all();
128
promise.allSettled();
129
promise.spread(fulfilled, rejected);
130
```
131
132
[Collection Operations](./collections.md)
133
134
### Flow Control and Timing
135
136
Utilities for controlling promise execution timing, delays, timeouts, and conditional processing.
137
138
```javascript { .api }
139
// Timing control
140
function Q.delay(object, timeout);
141
function Q.timeout(object, ms, message);
142
function Q.when(value, fulfilled, rejected, ms);
143
144
// Instance timing methods
145
promise.delay(ms);
146
promise.timeout(ms, message);
147
promise.finally(callback, ms);
148
```
149
150
[Flow Control](./flow-control.md)
151
152
### Functional Programming
153
154
Function wrappers and utilities for integrating promises with functional programming patterns.
155
156
```javascript { .api }
157
// Function wrapping
158
function Q.function(wrapped);
159
function Q.promised(callback);
160
function Q.join(x, y);
161
162
// Async/generator support
163
function Q.async(makeGenerator);
164
function Q.spawn(makeGenerator);
165
```
166
167
[Functional Programming](./functional.md)
168
169
### Node.js Integration
170
171
Comprehensive Node.js callback integration for converting existing callback-based APIs to promises.
172
173
```javascript { .api }
174
// Node.js callback conversion
175
function Q.denodeify(callback, pattern);
176
function Q.ninvoke(object, name, ...args);
177
178
// Instance Node.js methods
179
promise.ninvoke(name, ...args);
180
promise.nodeify(nodeback);
181
```
182
183
[Node.js Integration](./nodejs.md)
184
185
### Promise Chain Methods
186
187
Core promise instance methods for building promise chains with transformations and error handling.
188
189
```javascript { .api }
190
// Chain building
191
promise.then(fulfilled, rejected, ms);
192
promise.catch(rejected);
193
promise.done(fulfilled, rejected);
194
promise.finally(callback, ms);
195
196
// Value transformation
197
promise.thenResolve(value);
198
promise.thenReject(error);
199
```
200
201
[Promise Chains](./promise-chains.md)
202
203
### Property and Method Access
204
205
Methods for accessing properties and calling methods on promised values.
206
207
```javascript { .api }
208
// Property access
209
promise.get(name);
210
promise.keys();
211
212
// Method calling
213
promise.invoke(name, ...args);
214
promise.apply(thisp, args);
215
promise.call(thisp, ...args);
216
promise.bind(thisp, ...args);
217
```
218
219
[Property Access](./property-access.md)
220
221
### Advanced Operations
222
223
Advanced features including low-level dispatch, pass-by-copy semantics, and timing estimates.
224
225
```javascript { .api }
226
// Low-level operations
227
promise.dispatch(op, args);
228
promise.rawDispatch(resolve, op, args);
229
230
// Pass-by-copy
231
function Q.passByCopy(value);
232
function Q.isPortable(value);
233
promise.pass();
234
promise.toBePassed();
235
236
// Timing estimates
237
promise.observeEstimate(emit);
238
promise.getEstimate();
239
```
240
241
[Advanced Operations](./advanced.md)
242
243
### Queue Operations
244
245
FIFO queue implementation using promises for producer-consumer patterns.
246
247
```javascript { .api }
248
// Queue constructor and methods (from queue.js module)
249
function Queue();
250
queue.put(value);
251
queue.get();
252
```
253
254
[Queue Operations](./queue.md)
255
256
## Types
257
258
```javascript { .api }
259
// Core interfaces
260
interface Deferred {
261
promise: Promise;
262
resolve(value): void;
263
reject(reason): void;
264
setEstimate(estimate): void;
265
makeNodeResolver(unpack?): Function;
266
}
267
268
interface PromiseState {
269
state: "pending" | "fulfilled" | "rejected";
270
value?: any;
271
reason?: any;
272
}
273
274
// Configuration
275
interface QConfiguration {
276
longStackSupport: boolean;
277
onerror: Function;
278
isIntrospective: boolean;
279
}
280
```
281
282
## Error Handling
283
284
Q provides comprehensive error handling with long stack traces and global error handlers:
285
286
```javascript
287
// Enable long stack traces
288
Q.longStackSupport = true;
289
290
// Set global error handler
291
Q.onerror = function(error) {
292
console.error("Unhandled promise rejection:", error);
293
};
294
295
// Disable stack trace filtering for debugging
296
Q.isIntrospective = true;
297
298
// Promise-specific error handling
299
promise
300
.catch(error => {
301
// Handle specific errors
302
if (error instanceof TypeError) {
303
return "Default value";
304
}
305
throw error; // Re-throw unhandled errors
306
})
307
.done(); // Ensure uncaught errors are thrown
308
```