0
# Promise Interface
1
2
Chainable promise-like methods for handling request success, failure, and completion with modern async patterns. The request object returned by `reqwest()` provides methods that allow for elegant error handling and response processing.
3
4
## Capabilities
5
6
### Then Method
7
8
Handles successful and failed requests with optional separate callbacks.
9
10
```javascript { .api }
11
/**
12
* Handles successful and failed requests
13
* @param {Function} success - Success callback function
14
* @param {Function} fail - Optional failure callback function
15
* @returns {Object} Self for chaining
16
*/
17
then(success?: Function, fail?: Function): RequestPromise;
18
```
19
20
**Usage Examples:**
21
22
```javascript
23
// Success only
24
reqwest({ url: '/api/data' })
25
.then(function(response) {
26
console.log('Data received:', response);
27
});
28
29
// Success and failure
30
reqwest({ url: '/api/data' })
31
.then(
32
function(response) {
33
console.log('Success:', response);
34
},
35
function(xhr, type, error) {
36
console.log('Failed:', error);
37
}
38
);
39
40
// Chaining multiple then calls
41
reqwest({ url: '/api/users' })
42
.then(function(users) {
43
console.log('Got users:', users.length);
44
return reqwest({ url: '/api/posts' });
45
})
46
.then(function(posts) {
47
console.log('Got posts:', posts.length);
48
});
49
```
50
51
### Fail Method
52
53
Handles only failed requests, allowing for focused error handling.
54
55
```javascript { .api }
56
/**
57
* Handles failed requests only
58
* @param {Function} fn - Failure callback function
59
* @returns {Object} Self for chaining
60
*/
61
fail(fn: Function): RequestPromise;
62
```
63
64
**Usage Examples:**
65
66
```javascript
67
// Basic error handling
68
reqwest({ url: '/api/data' })
69
.fail(function(xhr, type, error) {
70
console.log('Request failed:', error);
71
console.log('Status:', xhr.status);
72
console.log('Error type:', type);
73
});
74
75
// Error handling with retry logic
76
reqwest({ url: '/api/unreliable' })
77
.fail(function(xhr, type, error) {
78
if (xhr.status === 503) {
79
console.log('Service unavailable, retrying in 2 seconds...');
80
setTimeout(() => {
81
this.retry();
82
}, 2000);
83
} else {
84
console.log('Permanent failure:', error);
85
}
86
});
87
88
// Multiple error handlers
89
reqwest({ url: '/api/data' })
90
.fail(function(xhr, type, error) {
91
console.log('Logging error:', error);
92
})
93
.fail(function(xhr, type, error) {
94
showUserErrorMessage('Failed to load data');
95
});
96
```
97
98
### Always Method
99
100
Executes callback regardless of success or failure, useful for cleanup operations.
101
102
```javascript { .api }
103
/**
104
* Executes callback regardless of success or failure
105
* @param {Function} fn - Callback function always executed
106
* @returns {Object} Self for chaining
107
*/
108
always(fn: Function): RequestPromise;
109
```
110
111
**Usage Examples:**
112
113
```javascript
114
// Cleanup operations
115
reqwest({ url: '/api/data' })
116
.always(function(xhr, type) {
117
hideLoadingSpinner();
118
console.log('Request completed with type:', type);
119
});
120
121
// Multiple always handlers
122
reqwest({ url: '/api/user-profile' })
123
.then(function(profile) {
124
updateUserInterface(profile);
125
})
126
.fail(function(xhr, type, error) {
127
showErrorMessage(error);
128
})
129
.always(function() {
130
enableFormSubmission();
131
updateLastRequestTime();
132
});
133
```
134
135
### Catch Method
136
137
Alias for the `fail()` method, providing familiar promise-style error handling.
138
139
```javascript { .api }
140
/**
141
* Handles failed requests (alias for fail method)
142
* @param {Function} fn - Failure callback function
143
* @returns {Object} Self for chaining
144
*/
145
catch(fn: Function): RequestPromise;
146
```
147
148
**Usage Examples:**
149
150
```javascript
151
// Promise-style error handling
152
reqwest({ url: '/api/data' })
153
.then(function(data) {
154
return processData(data);
155
})
156
.catch(function(xhr, type, error) {
157
console.log('Something went wrong:', error);
158
});
159
160
// Equivalent to using fail()
161
reqwest({ url: '/api/data' })
162
.catch(function(xhr, type, error) {
163
// Same as .fail(function(xhr, type, error) { ... })
164
handleError(error);
165
});
166
```
167
168
## Method Chaining Patterns
169
170
The promise-like interface supports various chaining patterns for complex async workflows:
171
172
### Sequential Requests
173
174
```javascript
175
// Load user, then user's posts, then post comments
176
reqwest({ url: '/api/user/123' })
177
.then(function(user) {
178
console.log('Loaded user:', user.name);
179
return reqwest({ url: `/api/user/${user.id}/posts` });
180
})
181
.then(function(posts) {
182
console.log('Loaded posts:', posts.length);
183
if (posts.length > 0) {
184
return reqwest({ url: `/api/post/${posts[0].id}/comments` });
185
}
186
})
187
.then(function(comments) {
188
if (comments) {
189
console.log('Loaded comments:', comments.length);
190
}
191
})
192
.catch(function(xhr, type, error) {
193
console.log('Pipeline failed:', error);
194
})
195
.always(function() {
196
console.log('Request pipeline complete');
197
});
198
```
199
200
### Error Recovery
201
202
```javascript
203
// Attempt primary endpoint, fallback to secondary
204
reqwest({ url: '/api/primary/data' })
205
.fail(function(xhr, type, error) {
206
console.log('Primary failed, trying fallback...');
207
return reqwest({ url: '/api/fallback/data' });
208
})
209
.then(function(data) {
210
console.log('Data loaded (from primary or fallback):', data);
211
})
212
.catch(function(xhr, type, error) {
213
console.log('Both endpoints failed:', error);
214
});
215
```
216
217
### Conditional Processing
218
219
```javascript
220
// Load data and conditionally make additional requests
221
reqwest({ url: '/api/initial-data' })
222
.then(function(data) {
223
console.log('Initial data loaded');
224
225
if (data.needsAdditionalData) {
226
return reqwest({ url: '/api/additional-data' });
227
} else {
228
return data; // Return original data if no additional request needed
229
}
230
})
231
.then(function(finalData) {
232
console.log('Final data ready:', finalData);
233
})
234
.catch(function(xhr, type, error) {
235
console.log('Request chain failed:', error);
236
});
237
```
238
239
### Parallel Processing Simulation
240
241
```javascript
242
// Simulate parallel requests (though each reqwest call is independent)
243
const userRequest = reqwest({ url: '/api/user/123' });
244
const postsRequest = reqwest({ url: '/api/posts' });
245
const settingsRequest = reqwest({ url: '/api/settings' });
246
247
let userData, postsData, settingsData;
248
let completedRequests = 0;
249
250
function checkAllComplete() {
251
completedRequests++;
252
if (completedRequests === 3) {
253
console.log('All data loaded:', { userData, postsData, settingsData });
254
}
255
}
256
257
userRequest
258
.then(function(data) { userData = data; })
259
.always(checkAllComplete);
260
261
postsRequest
262
.then(function(data) { postsData = data; })
263
.always(checkAllComplete);
264
265
settingsRequest
266
.then(function(data) { settingsData = data; })
267
.always(checkAllComplete);
268
```
269
270
### Abort Method
271
272
Aborts the current request and triggers failure callbacks.
273
274
```javascript { .api }
275
/**
276
* Aborts the current request
277
* @returns {Object} Self for chaining (though aborted requests can't continue)
278
*/
279
abort(): RequestPromise;
280
```
281
282
**Usage Examples:**
283
284
```javascript
285
// Abort after timeout
286
const request = reqwest({ url: '/api/large-data' });
287
288
setTimeout(function() {
289
request.abort();
290
console.log('Request aborted due to timeout');
291
}, 5000);
292
293
// Conditional abort
294
const uploadRequest = reqwest({
295
url: '/api/upload',
296
method: 'POST',
297
data: formData
298
});
299
300
// Cancel upload if user navigates away
301
window.addEventListener('beforeunload', function() {
302
uploadRequest.abort();
303
});
304
```
305
306
### Retry Method
307
308
Retries the request with the same options and configuration.
309
310
```javascript { .api }
311
/**
312
* Retries the request with the same options
313
* @returns {Object} New request object for the retry attempt
314
*/
315
retry(): RequestPromise;
316
```
317
318
**Usage Examples:**
319
320
```javascript
321
// Retry on server errors
322
let retryCount = 0;
323
const maxRetries = 3;
324
325
function makeRequest() {
326
return reqwest({ url: '/api/unreliable' })
327
.fail(function(xhr, type, error) {
328
if (xhr.status >= 500 && retryCount < maxRetries) {
329
retryCount++;
330
console.log(`Server error, retrying... (${retryCount}/${maxRetries})`);
331
setTimeout(() => {
332
makeRequest();
333
}, 1000 * retryCount); // Exponential backoff
334
} else {
335
console.log('Max retries reached or permanent error:', error);
336
}
337
});
338
}
339
340
// Usage with instance retry method
341
reqwest({ url: '/api/data' })
342
.fail(function(xhr, type, error) {
343
if (xhr.status === 503) {
344
console.log('Service unavailable, retrying...');
345
return this.retry();
346
}
347
});
348
```
349
350
## Callback Function Signatures
351
352
The promise interface callbacks receive specific parameters:
353
354
### Success Callback
355
356
```javascript { .api }
357
/**
358
* Success callback function signature
359
* @param {any} response - Parsed response data (JSON object, XML document, HTML, text, etc.)
360
*/
361
type SuccessCallback = (response: any) => any;
362
```
363
364
### Failure Callback
365
366
```javascript { .api }
367
/**
368
* Failure callback function signature
369
* @param {XMLHttpRequest} xhr - The XMLHttpRequest object that failed
370
* @param {string} message - Error message ('Request is aborted: timeout', 'Could not parse JSON', etc.)
371
* @param {any} error - Additional error context (parsing errors, etc.)
372
*/
373
type FailCallback = (xhr: XMLHttpRequest, message: string, error: any) => any;
374
```
375
376
### Always Callback
377
378
```javascript { .api }
379
/**
380
* Always callback function signature (called on both success and failure)
381
* @param {any} response - Response data (same as success callback) or XMLHttpRequest object (on error)
382
*/
383
type AlwaysCallback = (response: any) => void;
384
```
385
386
### Before Callback
387
388
```javascript { .api }
389
/**
390
* Before callback function signature (called before request is sent)
391
* @param {XMLHttpRequest} xhr - The XMLHttpRequest object before the request is sent
392
*/
393
type BeforeCallback = (xhr: XMLHttpRequest) => void;
394
```
395
396
## Integration with Traditional Callbacks
397
398
The promise-like interface works alongside traditional callback options:
399
400
```javascript
401
// Using both promise methods and traditional callbacks
402
reqwest({
403
url: '/api/data',
404
success: function(data) {
405
console.log('Traditional success callback');
406
},
407
error: function(xhr, type, err) {
408
console.log('Traditional error callback');
409
}
410
})
411
.then(function(data) {
412
console.log('Promise-style success');
413
})
414
.catch(function(xhr, type, err) {
415
console.log('Promise-style error');
416
})
417
.always(function() {
418
console.log('Promise-style cleanup');
419
});
420
```
421
422
Both callback styles will be executed, allowing for gradual migration to promise-style code while maintaining backward compatibility.