0
# Request Execution
1
2
Request execution, timeout management, retry logic, and response streaming capabilities for controlling how and when HTTP requests are executed.
3
4
## Capabilities
5
6
### Request Execution
7
8
Methods for executing configured requests with different callback and promise patterns.
9
10
```javascript { .api }
11
/**
12
* Execute the request with optional callback
13
* @param {function} [callback] - Callback function (err, res) => void
14
* @returns {Request} Request instance for chaining
15
*/
16
Request.prototype.end(callback?): Request;
17
18
/**
19
* Promise interface for request execution
20
* @param {function} resolve - Success callback
21
* @param {function} [reject] - Error callback
22
* @returns {Promise<Response>} Promise resolving to Response
23
*/
24
Request.prototype.then(resolve, reject?): Promise<Response>;
25
26
/**
27
* Promise error handling
28
* @param {function} reject - Error callback
29
* @returns {Promise<Response>} Promise for chaining
30
*/
31
Request.prototype.catch(reject): Promise<Response>;
32
```
33
34
**Usage Examples:**
35
36
```javascript
37
const superagent = require('superagent');
38
39
// Callback style
40
superagent
41
.get('https://api.example.com/users')
42
.end((err, res) => {
43
if (err) {
44
console.error('Request failed:', err);
45
return;
46
}
47
console.log('Success:', res.body);
48
});
49
50
// Promise with then/catch
51
superagent
52
.get('https://api.example.com/users')
53
.then(res => {
54
console.log('Success:', res.body);
55
})
56
.catch(err => {
57
console.error('Request failed:', err);
58
});
59
60
// Async/await
61
(async () => {
62
try {
63
const res = await superagent.get('https://api.example.com/users');
64
console.log('Success:', res.body);
65
} catch (err) {
66
console.error('Request failed:', err);
67
}
68
})();
69
70
// Promise with both resolve and reject
71
superagent
72
.get('https://api.example.com/users')
73
.then(
74
res => console.log('Success:', res.body),
75
err => console.error('Failed:', err)
76
);
77
```
78
79
### Timeout Management
80
81
Configure various timeout options for request execution.
82
83
```javascript { .api }
84
/**
85
* Set timeout options for request
86
* @param {number|object} options - Timeout in ms or options object
87
* @param {number} [options.deadline] - Overall request timeout
88
* @param {number} [options.response] - Time to wait for first response byte
89
* @param {number} [options.upload] - Upload timeout
90
* @returns {Request} Request instance for chaining
91
*/
92
Request.prototype.timeout(options): Request;
93
94
/**
95
* Clear any set timeouts
96
* @returns {Request} Request instance for chaining
97
*/
98
Request.prototype.clearTimeout(): Request;
99
```
100
101
**Usage Examples:**
102
103
```javascript
104
// Simple timeout (overall request)
105
superagent
106
.get('https://api.example.com/slow-endpoint')
107
.timeout(5000) // 5 seconds
108
.end((err, res) => {
109
if (err && err.timeout) {
110
console.error('Request timed out');
111
}
112
});
113
114
// Detailed timeout configuration
115
superagent
116
.post('https://api.example.com/upload')
117
.attach('file', '/path/to/large-file.zip')
118
.timeout({
119
deadline: 60000, // 60 seconds overall
120
response: 10000, // 10 seconds to get first response byte
121
upload: 30000 // 30 seconds for upload to complete
122
});
123
124
// Clear timeout
125
const request = superagent
126
.get('https://api.example.com/data')
127
.timeout(5000);
128
129
// Later, remove timeout
130
request.clearTimeout();
131
```
132
133
### Retry Logic
134
135
Configure automatic retry behavior for failed requests.
136
137
```javascript { .api }
138
/**
139
* Set retry configuration for failed requests
140
* @param {number|boolean} count - Number of retry attempts or true for default
141
* @param {function} [callback] - Custom retry condition function
142
* @returns {Request} Request instance for chaining
143
*/
144
Request.prototype.retry(count, callback?): Request;
145
```
146
147
**Usage Examples:**
148
149
```javascript
150
// Basic retry (default conditions)
151
superagent
152
.get('https://api.example.com/unreliable')
153
.retry(3) // Retry up to 3 times
154
.end((err, res) => {
155
if (err) {
156
console.error('Failed after retries:', err);
157
}
158
});
159
160
// Custom retry condition
161
superagent
162
.get('https://api.example.com/data')
163
.retry(3, (err, res) => {
164
// Custom logic to determine if retry should happen
165
if (err && err.code === 'ECONNRESET') return true; // Retry
166
if (res && res.status === 503) return true; // Retry
167
return false; // Don't retry
168
});
169
170
// Retry with promise
171
try {
172
const res = await superagent
173
.get('https://api.example.com/flaky')
174
.retry(2);
175
console.log('Success after retries:', res.body);
176
} catch (err) {
177
console.error('Failed even with retries:', err);
178
}
179
```
180
181
### Request Cancellation
182
183
Abort requests before completion.
184
185
```javascript { .api }
186
/**
187
* Abort the request
188
* @returns {Request} Request instance for chaining
189
*/
190
Request.prototype.abort(): Request;
191
```
192
193
**Usage Examples:**
194
195
```javascript
196
// Abort request after timeout
197
const request = superagent.get('https://api.example.com/slow');
198
199
setTimeout(() => {
200
request.abort();
201
console.log('Request aborted');
202
}, 3000);
203
204
request.end((err, res) => {
205
if (err && err.aborted) {
206
console.log('Request was aborted');
207
}
208
});
209
210
// Abort with promise
211
const controller = {
212
request: null,
213
abort() {
214
if (this.request) {
215
this.request.abort();
216
}
217
}
218
};
219
220
controller.request = superagent.get('https://api.example.com/data');
221
222
// Later, abort the request
223
controller.abort();
224
225
try {
226
const res = await controller.request;
227
} catch (err) {
228
if (err.aborted) {
229
console.log('Request was aborted');
230
}
231
}
232
```
233
234
### Response Streaming
235
236
Stream responses to files or other streams.
237
238
```javascript { .api }
239
/**
240
* Pipe response to a writable stream
241
* @param {Stream} stream - Writable stream destination
242
* @param {object} [options] - Pipe options
243
* @returns {Stream} The destination stream
244
*/
245
Request.prototype.pipe(stream, options?): Stream;
246
247
/**
248
* Write data to request (for streaming uploads)
249
* @param {Buffer|string} data - Data to write
250
* @param {string} [encoding] - Encoding for string data
251
* @returns {boolean} Whether write was successful
252
*/
253
Request.prototype.write(data, encoding?): boolean;
254
```
255
256
**Usage Examples:**
257
258
```javascript
259
const fs = require('fs');
260
261
// Stream response to file
262
superagent
263
.get('https://api.example.com/large-file.zip')
264
.pipe(fs.createWriteStream('/path/to/downloaded-file.zip'))
265
.on('finish', () => {
266
console.log('File downloaded successfully');
267
})
268
.on('error', (err) => {
269
console.error('Download failed:', err);
270
});
271
272
// Stream with progress tracking
273
const writeStream = fs.createWriteStream('/path/to/file.zip');
274
const request = superagent.get('https://api.example.com/file.zip');
275
276
request.on('progress', (event) => {
277
console.log(`Download progress: ${event.percent}%`);
278
});
279
280
request.pipe(writeStream);
281
282
// Stream upload data
283
const uploadStream = superagent
284
.post('https://api.example.com/stream-upload')
285
.type('application/octet-stream');
286
287
// Write data to upload stream
288
uploadStream.write(Buffer.from('chunk 1'));
289
uploadStream.write(Buffer.from('chunk 2'));
290
uploadStream.end(); // Signal end of upload
291
292
uploadStream.then(res => {
293
console.log('Stream upload complete:', res.body);
294
});
295
```
296
297
### Custom Success Conditions
298
299
Define custom conditions for successful responses.
300
301
```javascript { .api }
302
/**
303
* Set custom success condition function
304
* @param {function} fn - Function that returns true for successful responses
305
* @returns {Request} Request instance for chaining
306
*/
307
Request.prototype.ok(fn): Request;
308
```
309
310
**Usage Examples:**
311
312
```javascript
313
// Accept 4xx status codes as success
314
superagent
315
.get('https://api.example.com/data')
316
.ok(res => res.status < 500) // Treat anything below 500 as success
317
.end((err, res) => {
318
// err will be null for 4xx responses
319
if (!err) {
320
console.log('Request succeeded:', res.status);
321
}
322
});
323
324
// Custom business logic success condition
325
superagent
326
.get('https://api.example.com/check')
327
.ok(res => {
328
// Custom logic based on response body
329
return res.body && res.body.success === true;
330
})
331
.end((err, res) => {
332
if (!err) {
333
console.log('Business logic success');
334
}
335
});
336
337
// Multiple success conditions
338
superagent
339
.get('https://api.example.com/data')
340
.ok(res => {
341
// Success if status is 200-299 or specific 4xx codes
342
return (res.status >= 200 && res.status < 300) ||
343
res.status === 404 ||
344
res.status === 410;
345
});
346
```
347
348
### Event Handling
349
350
Handle request and response events.
351
352
```javascript { .api }
353
/**
354
* Add event listener to request
355
* @param {string} event - Event name
356
* @param {function} listener - Event handler function
357
* @returns {Request} Request instance for chaining
358
*/
359
Request.prototype.on(event, listener): Request;
360
361
/**
362
* Add one-time event listener to request
363
* @param {string} event - Event name
364
* @param {function} listener - Event handler function
365
* @returns {Request} Request instance for chaining
366
*/
367
Request.prototype.once(event, listener): Request;
368
```
369
370
**Usage Examples:**
371
372
```javascript
373
// Progress tracking
374
superagent
375
.post('https://api.example.com/upload')
376
.attach('file', '/path/to/large-file.zip')
377
.on('progress', (event) => {
378
if (event.direction === 'upload') {
379
console.log(`Upload: ${event.percent}% (${event.loaded}/${event.total})`);
380
} else {
381
console.log(`Download: ${event.percent}%`);
382
}
383
})
384
.on('error', (err) => {
385
console.error('Request error:', err);
386
})
387
.on('response', (res) => {
388
console.log('Response received:', res.status);
389
})
390
.end();
391
392
// One-time event listeners
393
superagent
394
.get('https://api.example.com/data')
395
.once('response', (res) => {
396
console.log('First response received:', res.status);
397
})
398
.once('error', (err) => {
399
console.error('Request failed:', err);
400
});
401
```