0
# Synchronous Inspection
1
2
Optional methods for synchronously inspecting promise state. These methods are disabled by default for performance reasons and must be explicitly enabled.
3
4
## Capabilities
5
6
### Promise.enableSynchronous
7
8
Enables synchronous inspection methods on Promise.prototype.
9
10
```javascript { .api }
11
/**
12
* Enables synchronous inspection methods
13
* Adds isPending, isFulfilled, isRejected, getValue, getReason, getState to prototype
14
* @returns {void}
15
*/
16
Promise.enableSynchronous();
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
const Promise = require('promise');
23
24
// Enable synchronous inspection
25
Promise.enableSynchronous();
26
27
const resolved = Promise.resolve('hello');
28
const rejected = Promise.reject(new Error('failed'));
29
const pending = new Promise(() => {}); // Never resolves
30
31
console.log(resolved.isFulfilled()); // true
32
console.log(rejected.isRejected()); // true
33
console.log(pending.isPending()); // true
34
```
35
36
### Promise.disableSynchronous
37
38
Disables synchronous inspection methods by removing them from Promise.prototype.
39
40
```javascript { .api }
41
/**
42
* Disables synchronous inspection methods
43
* Removes isPending, isFulfilled, isRejected, getValue, getReason, getState from prototype
44
* @returns {void}
45
*/
46
Promise.disableSynchronous();
47
```
48
49
**Usage Examples:**
50
51
```javascript
52
const Promise = require('promise');
53
54
Promise.enableSynchronous();
55
const promise = Promise.resolve('test');
56
57
console.log(typeof promise.isFulfilled); // 'function'
58
59
Promise.disableSynchronous();
60
console.log(typeof promise.isFulfilled); // 'undefined'
61
```
62
63
## Instance Methods (Available after enableSynchronous)
64
65
### isPending
66
67
Checks if the promise is still pending (not yet settled).
68
69
```javascript { .api }
70
/**
71
* Checks if promise is pending
72
* @returns {boolean} True if promise is pending
73
*/
74
Promise.prototype.isPending();
75
```
76
77
### isFulfilled
78
79
Checks if the promise has been fulfilled with a value.
80
81
```javascript { .api }
82
/**
83
* Checks if promise is fulfilled
84
* @returns {boolean} True if promise is fulfilled
85
*/
86
Promise.prototype.isFulfilled();
87
```
88
89
### isRejected
90
91
Checks if the promise has been rejected with a reason.
92
93
```javascript { .api }
94
/**
95
* Checks if promise is rejected
96
* @returns {boolean} True if promise is rejected
97
*/
98
Promise.prototype.isRejected();
99
```
100
101
### getValue
102
103
Synchronously retrieves the fulfillment value from a fulfilled promise.
104
105
```javascript { .api }
106
/**
107
* Gets the fulfillment value
108
* @returns {*} The fulfillment value
109
* @throws {Error} If promise is not fulfilled
110
*/
111
Promise.prototype.getValue();
112
```
113
114
### getReason
115
116
Synchronously retrieves the rejection reason from a rejected promise.
117
118
```javascript { .api }
119
/**
120
* Gets the rejection reason
121
* @returns {*} The rejection reason
122
* @throws {Error} If promise is not rejected
123
*/
124
Promise.prototype.getReason();
125
```
126
127
### getState
128
129
Gets the numeric state of the promise.
130
131
```javascript { .api }
132
/**
133
* Gets the promise state
134
* @returns {number} 0=pending, 1=fulfilled, 2=rejected
135
*/
136
Promise.prototype.getState();
137
```
138
139
## Usage Examples
140
141
### Basic State Inspection
142
143
```javascript
144
const Promise = require('promise');
145
146
Promise.enableSynchronous();
147
148
// Test different promise states
149
const promises = {
150
resolved: Promise.resolve('success'),
151
rejected: Promise.reject(new Error('failure')),
152
pending: new Promise(() => {}) // Never settles
153
};
154
155
Object.entries(promises).forEach(([name, promise]) => {
156
console.log(`${name}:`);
157
console.log(' isPending:', promise.isPending());
158
console.log(' isFulfilled:', promise.isFulfilled());
159
console.log(' isRejected:', promise.isRejected());
160
console.log(' getState:', promise.getState());
161
});
162
```
163
164
### Safe Value/Reason Retrieval
165
166
```javascript
167
const Promise = require('promise');
168
169
Promise.enableSynchronous();
170
171
function safeGetValue(promise) {
172
if (promise.isFulfilled()) {
173
return promise.getValue();
174
} else if (promise.isRejected()) {
175
return `Error: ${promise.getReason().message}`;
176
} else {
177
return 'Still pending';
178
}
179
}
180
181
const promise1 = Promise.resolve('Hello World');
182
const promise2 = Promise.reject(new Error('Something failed'));
183
184
console.log(safeGetValue(promise1)); // "Hello World"
185
console.log(safeGetValue(promise2)); // "Error: Something failed"
186
```
187
188
### Testing and Debugging
189
190
```javascript
191
const Promise = require('promise');
192
193
Promise.enableSynchronous();
194
195
function debugPromise(promise, label) {
196
console.log(`${label}:`);
197
console.log(` State: ${promise.getState()} (${getStateText(promise)})`);
198
199
try {
200
if (promise.isFulfilled()) {
201
console.log(` Value:`, promise.getValue());
202
} else if (promise.isRejected()) {
203
console.log(` Reason:`, promise.getReason());
204
}
205
} catch (error) {
206
console.log(` Error accessing value/reason:`, error.message);
207
}
208
}
209
210
function getStateText(promise) {
211
if (promise.isPending()) return 'pending';
212
if (promise.isFulfilled()) return 'fulfilled';
213
if (promise.isRejected()) return 'rejected';
214
return 'unknown';
215
}
216
217
// Debug promises at different states
218
debugPromise(Promise.resolve(42), 'Resolved Promise');
219
debugPromise(Promise.reject(new Error('test')), 'Rejected Promise');
220
```
221
222
### Synchronous Testing
223
224
```javascript
225
const Promise = require('promise');
226
227
Promise.enableSynchronous();
228
229
// Useful for unit tests
230
function createImmediatePromise(value, shouldReject = false) {
231
return shouldReject ? Promise.reject(value) : Promise.resolve(value);
232
}
233
234
// Test synchronously
235
const success = createImmediatePromise('test data');
236
const failure = createImmediatePromise(new Error('test error'), true);
237
238
// Assert states immediately
239
console.assert(success.isFulfilled());
240
console.assert(success.getValue() === 'test data');
241
242
console.assert(failure.isRejected());
243
console.assert(failure.getReason().message === 'test error');
244
```
245
246
## Performance Considerations
247
248
- **Disabled by default**: Synchronous inspection adds overhead to all promises
249
- **Enable selectively**: Only enable during development or testing
250
- **Production usage**: Generally not recommended for production code
251
- **Alternative approaches**: Consider using `.then()` and `.catch()` for normal promise handling
252
253
## Error Conditions
254
255
```javascript
256
const Promise = require('promise');
257
258
Promise.enableSynchronous();
259
260
const pending = new Promise(() => {});
261
const resolved = Promise.resolve('value');
262
const rejected = Promise.reject(new Error('reason'));
263
264
// These will throw errors:
265
try {
266
pending.getValue(); // Error: Cannot get value of unfulfilled promise
267
} catch (e) {
268
console.log(e.message);
269
}
270
271
try {
272
resolved.getReason(); // Error: Cannot get rejection reason of non-rejected promise
273
} catch (e) {
274
console.log(e.message);
275
}
276
```