0
# Promise State and Inspection
1
2
Methods for examining promise state, extracting information about promise fulfillment status, and runtime type checking.
3
4
## Capabilities
5
6
### Promise Type Testing
7
8
Functions for determining if objects are Q promises and checking promise-like behavior.
9
10
```javascript { .api }
11
/**
12
* Tests if object is a Q promise
13
* @param object - Object to test
14
* @returns True if object is a Q promise
15
*/
16
function Q.isPromise(object);
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
const Q = require("q");
23
24
// Test different object types
25
const regularPromise = Q.resolve("value");
26
const nativePromise = Promise.resolve("native");
27
const thenable = { then: (resolve) => resolve("thenable") };
28
const regularObject = { value: "not a promise" };
29
30
console.log(Q.isPromise(regularPromise)); // true
31
console.log(Q.isPromise(nativePromise)); // false (not a Q promise)
32
console.log(Q.isPromise(thenable)); // false (thenable but not Q promise)
33
console.log(Q.isPromise(regularObject)); // false
34
35
// Use in conditional logic
36
function handleInput(input) {
37
if (Q.isPromise(input)) {
38
return input.then(value => processValue(value));
39
} else {
40
return Q.resolve(processValue(input));
41
}
42
}
43
44
// Type checking in error handling
45
function safeProcess(maybePromise) {
46
try {
47
if (Q.isPromise(maybePromise)) {
48
return maybePromise.catch(error => {
49
console.error("Promise rejected:", error);
50
return "default value";
51
});
52
} else {
53
return Q.resolve(maybePromise);
54
}
55
} catch (error) {
56
console.error("Synchronous error:", error);
57
return Q.reject(error);
58
}
59
}
60
```
61
62
### State Inspection
63
64
Methods for examining the current state of promises and extracting their values or reasons.
65
66
```javascript { .api }
67
/**
68
* Returns snapshot of promise state
69
* @returns Object with state information {state, value?, reason?}
70
*/
71
promise.inspect();
72
73
/**
74
* Tests if promise is waiting for result
75
* @returns True if promise is pending
76
*/
77
promise.isPending();
78
79
/**
80
* Tests if promise has fulfillment value
81
* @returns True if promise is fulfilled
82
*/
83
promise.isFulfilled();
84
85
/**
86
* Tests if promise has rejection reason
87
* @returns True if promise is rejected
88
*/
89
promise.isRejected();
90
```
91
92
**Usage Examples:**
93
94
```javascript
95
const Q = require("q");
96
97
// Inspect promise states
98
const pendingPromise = Q.delay("result", 1000);
99
const fulfilledPromise = Q.resolve("success");
100
const rejectedPromise = Q.reject(new Error("failure"));
101
102
console.log(pendingPromise.inspect());
103
// { state: "pending" }
104
105
console.log(fulfilledPromise.inspect());
106
// { state: "fulfilled", value: "success" }
107
108
console.log(rejectedPromise.inspect());
109
// { state: "rejected", reason: Error("failure") }
110
111
// Use state checking methods
112
console.log(pendingPromise.isPending()); // true
113
console.log(fulfilledPromise.isFulfilled()); // true
114
console.log(rejectedPromise.isRejected()); // true
115
116
// Conditional processing based on state
117
function processPromiseArray(promises) {
118
const results = promises.map(promise => {
119
const inspection = promise.inspect();
120
121
switch (inspection.state) {
122
case "fulfilled":
123
return { success: true, data: inspection.value };
124
case "rejected":
125
return { success: false, error: inspection.reason.message };
126
case "pending":
127
return { success: false, error: "Still pending" };
128
default:
129
return { success: false, error: "Unknown state" };
130
}
131
});
132
133
return results;
134
}
135
136
// Monitoring promise progress
137
function monitorPromise(promise, name) {
138
const startTime = Date.now();
139
140
const checkStatus = () => {
141
const elapsed = Date.now() - startTime;
142
const inspection = promise.inspect();
143
144
console.log(`[${elapsed}ms] ${name}: ${inspection.state}`);
145
146
if (inspection.state === "pending") {
147
setTimeout(checkStatus, 100); // Check again in 100ms
148
} else if (inspection.state === "fulfilled") {
149
console.log(`[${elapsed}ms] ${name}: completed with value:`, inspection.value);
150
} else {
151
console.log(`[${elapsed}ms] ${name}: failed with error:`, inspection.reason.message);
152
}
153
};
154
155
checkStatus();
156
return promise;
157
}
158
159
// Usage
160
const slowOperation = Q.delay("finished", 2000);
161
monitorPromise(slowOperation, "Slow Operation");
162
```
163
164
### String Representation
165
166
Methods for converting promises to string representations for debugging and logging.
167
168
```javascript { .api }
169
/**
170
* Returns string representation of promise
171
* @returns "[object Promise]"
172
*/
173
promise.toString();
174
```
175
176
**Usage Examples:**
177
178
```javascript
179
const Q = require("q");
180
181
// String representation
182
const promise = Q.resolve("test");
183
console.log(promise.toString()); // "[object Promise]"
184
185
// Use in logging
186
function logPromise(promise, name) {
187
console.log(`Promise ${name}: ${promise.toString()}`);
188
console.log(`State: ${promise.inspect().state}`);
189
190
return promise.then(
191
value => {
192
console.log(`Promise ${name} fulfilled with:`, value);
193
return value;
194
},
195
error => {
196
console.log(`Promise ${name} rejected with:`, error.message);
197
throw error;
198
}
199
);
200
}
201
202
// Debug helper
203
function debugPromise(promise) {
204
const inspection = promise.inspect();
205
const stringRep = promise.toString();
206
207
return {
208
string: stringRep,
209
state: inspection.state,
210
value: inspection.value,
211
reason: inspection.reason,
212
isPending: promise.isPending(),
213
isFulfilled: promise.isFulfilled(),
214
isRejected: promise.isRejected()
215
};
216
}
217
218
// Usage
219
const testPromise = Q.delay("result", 500);
220
console.log("Debug info:", debugPromise(testPromise));
221
222
setTimeout(() => {
223
console.log("Debug info after delay:", debugPromise(testPromise));
224
}, 600);
225
```
226
227
### Advanced State Queries
228
229
Advanced methods for examining promise state in complex scenarios.
230
231
```javascript { .api }
232
/**
233
* Inspection state object interface
234
*/
235
interface InspectionState {
236
state: "pending" | "fulfilled" | "rejected";
237
value?: any; // Present when state is "fulfilled"
238
reason?: any; // Present when state is "rejected"
239
}
240
```
241
242
**Usage Examples:**
243
244
```javascript
245
const Q = require("q");
246
247
// Batch state analysis
248
function analyzePromiseBatch(promises) {
249
const analysis = {
250
total: promises.length,
251
pending: 0,
252
fulfilled: 0,
253
rejected: 0,
254
values: [],
255
errors: []
256
};
257
258
promises.forEach(promise => {
259
const inspection = promise.inspect();
260
261
switch (inspection.state) {
262
case "pending":
263
analysis.pending++;
264
break;
265
case "fulfilled":
266
analysis.fulfilled++;
267
analysis.values.push(inspection.value);
268
break;
269
case "rejected":
270
analysis.rejected++;
271
analysis.errors.push(inspection.reason);
272
break;
273
}
274
});
275
276
return analysis;
277
}
278
279
// Promise pool monitoring
280
class PromisePool {
281
constructor() {
282
this.promises = new Map();
283
}
284
285
add(name, promise) {
286
this.promises.set(name, promise);
287
return promise;
288
}
289
290
getStatus() {
291
const status = {};
292
293
this.promises.forEach((promise, name) => {
294
const inspection = promise.inspect();
295
status[name] = {
296
state: inspection.state,
297
hasValue: inspection.hasOwnProperty("value"),
298
hasReason: inspection.hasOwnProperty("reason")
299
};
300
});
301
302
return status;
303
}
304
305
getCompleted() {
306
const completed = [];
307
308
this.promises.forEach((promise, name) => {
309
if (!promise.isPending()) {
310
completed.push({ name, promise });
311
}
312
});
313
314
return completed;
315
}
316
}
317
318
// Usage
319
const pool = new PromisePool();
320
pool.add("fast", Q.delay("fast result", 100));
321
pool.add("slow", Q.delay("slow result", 500));
322
pool.add("error", Q.reject(new Error("test error")));
323
324
setTimeout(() => {
325
console.log("Pool status:", pool.getStatus());
326
console.log("Completed:", pool.getCompleted().map(c => c.name));
327
}, 200);
328
```