Skip to content

Commit e31282d

Browse files
jottosindresorhus
authored andcommitted
Fix cancel when timeout exists - fixes #344 (#360)
1 parent 4b49df2 commit e31282d

2 files changed

Lines changed: 25 additions & 2 deletions

File tree

index.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,7 @@ function asPromise(opts) {
270270

271271
const proxy = new EventEmitter();
272272

273-
const promise = timeoutFn(new PCancelable((onCancel, resolve, reject) => {
273+
const cancelable = new PCancelable((onCancel, resolve, reject) => {
274274
const ee = requestAsEventEmitter(opts);
275275
let cancelOnRequest = false;
276276

@@ -332,7 +332,11 @@ function asPromise(opts) {
332332
ee.on('error', reject);
333333
ee.on('uploadProgress', proxy.emit.bind(proxy, 'uploadProgress'));
334334
ee.on('downloadProgress', proxy.emit.bind(proxy, 'downloadProgress'));
335-
}));
335+
});
336+
337+
const promise = timeoutFn(cancelable);
338+
339+
promise.cancel = cancelable.cancel.bind(cancelable);
336340

337341
promise.on = (name, fn) => {
338342
proxy.on(name, fn);

test/cancel.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,25 @@ test('cancel in-progress request', async t => {
4747
await t.notThrows(helper.aborted, 'Request finished instead of aborting.');
4848
});
4949

50+
test('cancel in-progress request with timeout', async t => {
51+
const helper = await createAbortServer();
52+
const body = new Readable({
53+
read() {}
54+
});
55+
body.push('1');
56+
57+
const p = got(helper.url, {body, timeout: 10000});
58+
59+
// Wait for the stream to be established before canceling
60+
setTimeout(() => {
61+
p.cancel();
62+
body.push(null);
63+
}, 100);
64+
65+
await t.throws(p, PCancelable.CancelError);
66+
await t.notThrows(helper.aborted, 'Request finished instead of aborting.');
67+
});
68+
5069
test('cancel immediately', async t => {
5170
const s = await createServer();
5271
const aborted = new Promise((resolve, reject) => {

0 commit comments

Comments
 (0)