0
# Promise Chain Methods
1
2
Core promise instance methods for building promise chains with transformations, error handling, and chain termination.
3
4
## Capabilities
5
6
### Then Method
7
8
The fundamental promise chaining method for handling fulfillment and rejection.
9
10
```javascript { .api }
11
/**
12
* Standard promise then with optional timing estimate
13
* @param fulfilled - Callback for successful resolution
14
* @param rejected - Optional callback for rejection handling
15
* @param ms - Optional timing estimate in milliseconds
16
* @returns New promise for the callback result
17
*/
18
promise.then(fulfilled, rejected, ms);
19
```
20
21
**Usage Examples:**
22
23
```javascript
24
const Q = require("q");
25
26
// Basic then usage
27
Q.resolve("Hello")
28
.then(value => value.toUpperCase())
29
.then(value => console.log(value)) // "HELLO"
30
.catch(error => console.error(error));
31
32
// With both success and error handlers
33
fetchUser(123)
34
.then(
35
user => {
36
console.log("User loaded:", user.name);
37
return user.email;
38
},
39
error => {
40
console.error("Failed to load user:", error.message);
41
return "default@example.com";
42
}
43
)
44
.then(email => sendWelcomeEmail(email));
45
46
// With timing estimate
47
Q.resolve(complexData)
48
.then(data => {
49
return processComplexData(data);
50
}, undefined, 5000) // Estimate 5 seconds for processing
51
.then(result => console.log("Processing complete:", result));
52
53
// Chaining multiple transformations
54
fetchUserData()
55
.then(data => validateData(data))
56
.then(validData => enrichData(validData))
57
.then(enrichedData => saveToDatabase(enrichedData))
58
.then(savedData => notifyUser(savedData.id))
59
.catch(error => handleError(error));
60
```
61
62
### Catch Method
63
64
Specialized error handling method for promise chains.
65
66
```javascript { .api }
67
/**
68
* Handles rejections (alias for then(undefined, rejected))
69
* @param rejected - Callback for rejection handling
70
* @returns New promise for the error handler result
71
*/
72
promise.catch(rejected);
73
```
74
75
**Usage Examples:**
76
77
```javascript
78
const Q = require("q");
79
80
// Basic error handling
81
Q.reject(new Error("Something went wrong"))
82
.catch(error => {
83
console.error("Caught error:", error.message);
84
return "default value";
85
})
86
.then(value => console.log("Result:", value));
87
88
// Specific error handling
89
fetchDataFromAPI()
90
.catch(error => {
91
if (error.code === "NETWORK_ERROR") {
92
console.log("Network issue, trying cache...");
93
return fetchFromCache();
94
} else if (error.code === "AUTH_ERROR") {
95
console.log("Authentication failed, redirecting...");
96
redirectToLogin();
97
throw error;
98
} else {
99
console.error("Unexpected error:", error);
100
throw error;
101
}
102
})
103
.then(data => processData(data))
104
.catch(error => showErrorToUser(error.message));
105
106
// Error recovery patterns
107
function robustDataFetch(url) {
108
return fetch(url)
109
.catch(error => {
110
console.log("Primary fetch failed, trying backup...");
111
return fetch(url.replace("api", "backup-api"));
112
})
113
.catch(error => {
114
console.log("Backup fetch failed, using cached data...");
115
return getCachedData(url);
116
})
117
.catch(error => {
118
console.log("Cache miss, using default data...");
119
return getDefaultData();
120
});
121
}
122
```
123
124
### Done Method
125
126
Terminates promise chains and ensures uncaught errors are thrown.
127
128
```javascript { .api }
129
/**
130
* Terminates chain, forces exceptions to be thrown
131
* @param fulfilled - Optional callback for successful resolution
132
* @param rejected - Optional callback for rejection handling
133
* @returns void (does not return a promise)
134
*/
135
promise.done(fulfilled, rejected);
136
```
137
138
**Usage Examples:**
139
140
```javascript
141
const Q = require("q");
142
143
// Basic chain termination
144
fetchUserData()
145
.then(data => processData(data))
146
.then(result => updateUI(result))
147
.catch(error => showErrorMessage(error))
148
.done(); // Ensures any uncaught errors are thrown
149
150
// With success handler
151
Q.resolve("important data")
152
.then(data => criticalOperation(data))
153
.done(
154
result => console.log("Operation succeeded:", result),
155
error => console.error("Critical operation failed:", error)
156
);
157
158
// Ensuring error propagation
159
function criticalProcess() {
160
return loadConfiguration()
161
.then(config => validateConfiguration(config))
162
.then(validConfig => initializeSystem(validConfig))
163
.catch(error => {
164
console.error("System initialization failed:", error);
165
process.exit(1); // Critical failure
166
})
167
.done(); // Ensure any programming errors are thrown
168
}
169
170
// Fire-and-forget operations
171
function backgroundTask() {
172
cleanupTempFiles()
173
.then(() => updateMetrics())
174
.then(() => sendHeartbeat())
175
.catch(error => logError("Background task failed:", error))
176
.done(); // Don't return promise, just ensure completion
177
}
178
```
179
180
### Finally Method (inherited from flow-control)
181
182
Executes cleanup code regardless of promise resolution or rejection.
183
184
```javascript { .api }
185
/**
186
* Executes callback regardless of fulfillment or rejection
187
* @param callback - Function to execute for cleanup
188
* @param ms - Optional timing estimate
189
* @returns Promise that preserves original result
190
*/
191
promise.finally(callback, ms);
192
```
193
194
**Usage Examples:**
195
196
```javascript
197
const Q = require("q");
198
199
// Database connection cleanup
200
function queryDatabase(sql) {
201
let connection;
202
203
return connectToDatabase()
204
.then(conn => {
205
connection = conn;
206
return connection.query(sql);
207
})
208
.finally(() => {
209
if (connection) {
210
connection.close();
211
console.log("Database connection closed");
212
}
213
});
214
}
215
216
// Loading state management
217
function performLongOperation() {
218
showLoadingSpinner();
219
220
return longRunningTask()
221
.then(result => {
222
showSuccessMessage("Operation completed");
223
return result;
224
})
225
.catch(error => {
226
showErrorMessage("Operation failed: " + error.message);
227
throw error;
228
})
229
.finally(() => {
230
hideLoadingSpinner();
231
});
232
}
233
```
234
235
### Value Transformation Methods
236
237
Methods for transforming promise values regardless of the original outcome.
238
239
```javascript { .api }
240
/**
241
* Resolves to specific value regardless of original result
242
* @param value - Value to resolve with
243
* @returns Promise that resolves to the specified value
244
*/
245
promise.thenResolve(value);
246
247
/**
248
* Rejects with specific error regardless of original result
249
* @param error - Error to reject with
250
* @returns Promise that rejects with the specified error
251
*/
252
promise.thenReject(error);
253
```
254
255
**Usage Examples:**
256
257
```javascript
258
const Q = require("q");
259
260
// Transform any outcome to success
261
checkPermissions()
262
.thenResolve("access granted")
263
.then(message => console.log(message));
264
265
// Transform any outcome to failure
266
deprecatedFunction()
267
.thenReject(new Error("This function is deprecated"))
268
.catch(error => console.error(error.message));
269
270
// Conditional transformation
271
function processWithDefault(promise, defaultValue) {
272
return promise
273
.catch(error => {
274
console.log("Operation failed, using default");
275
return Q.resolve().thenResolve(defaultValue);
276
});
277
}
278
279
// Status code transformation
280
function apiCall(endpoint) {
281
return httpRequest(endpoint)
282
.then(response => {
283
if (response.status === 200) {
284
return response.data;
285
} else {
286
return Q.resolve().thenReject(
287
new Error(`API error: ${response.status}`)
288
);
289
}
290
});
291
}
292
```
293
294
## Chain Composition Patterns
295
296
### Sequential Processing
297
298
```javascript
299
const Q = require("q");
300
301
// Process items sequentially
302
function processSequentially(items, processor) {
303
return items.reduce((promise, item) => {
304
return promise.then(results => {
305
return processor(item).then(result => {
306
results.push(result);
307
return results;
308
});
309
});
310
}, Q.resolve([]));
311
}
312
313
// Usage
314
const items = [1, 2, 3, 4, 5];
315
processSequentially(items, num => Q.delay(num * 2, 100))
316
.then(results => console.log("Sequential results:", results))
317
.done();
318
```
319
320
### Conditional Chaining
321
322
```javascript
323
const Q = require("q");
324
325
// Conditional promise chains
326
function conditionalProcess(data, condition) {
327
return Q.resolve(data)
328
.then(data => {
329
if (condition(data)) {
330
return expensiveOperation(data);
331
} else {
332
return quickOperation(data);
333
}
334
})
335
.then(result => finalizeResult(result));
336
}
337
338
// Branch and merge pattern
339
function branchAndMerge(input) {
340
return Q.resolve(input)
341
.then(data => {
342
if (data.type === "premium") {
343
return premiumProcessing(data)
344
.then(result => ({ ...result, tier: "premium" }));
345
} else {
346
return standardProcessing(data)
347
.then(result => ({ ...result, tier: "standard" }));
348
}
349
})
350
.then(result => applyCommonPostProcessing(result));
351
}
352
```