Browse Source

Fix cancel when timeout exists - fixes #344 (#360)

no-retry
Jonathan Otto 8 years ago
committed by Sindre Sorhus
parent
commit
e31282dfd3
  1. 8
      index.js
  2. 19
      test/cancel.js

8
index.js

@ -270,7 +270,7 @@ function asPromise(opts) {
const proxy = new EventEmitter(); const proxy = new EventEmitter();
const promise = timeoutFn(new PCancelable((onCancel, resolve, reject) => { const cancelable = new PCancelable((onCancel, resolve, reject) => {
const ee = requestAsEventEmitter(opts); const ee = requestAsEventEmitter(opts);
let cancelOnRequest = false; let cancelOnRequest = false;
@ -332,7 +332,11 @@ function asPromise(opts) {
ee.on('error', reject); ee.on('error', reject);
ee.on('uploadProgress', proxy.emit.bind(proxy, 'uploadProgress')); ee.on('uploadProgress', proxy.emit.bind(proxy, 'uploadProgress'));
ee.on('downloadProgress', proxy.emit.bind(proxy, 'downloadProgress')); ee.on('downloadProgress', proxy.emit.bind(proxy, 'downloadProgress'));
})); });
const promise = timeoutFn(cancelable);
promise.cancel = cancelable.cancel.bind(cancelable);
promise.on = (name, fn) => { promise.on = (name, fn) => {
proxy.on(name, fn); proxy.on(name, fn);

19
test/cancel.js

@ -47,6 +47,25 @@ test('cancel in-progress request', async t => {
await t.notThrows(helper.aborted, 'Request finished instead of aborting.'); await t.notThrows(helper.aborted, 'Request finished instead of aborting.');
}); });
test('cancel in-progress request with timeout', async t => {
const helper = await createAbortServer();
const body = new Readable({
read() {}
});
body.push('1');
const p = got(helper.url, {body, timeout: 10000});
// Wait for the stream to be established before canceling
setTimeout(() => {
p.cancel();
body.push(null);
}, 100);
await t.throws(p, PCancelable.CancelError);
await t.notThrows(helper.aborted, 'Request finished instead of aborting.');
});
test('cancel immediately', async t => { test('cancel immediately', async t => {
const s = await createServer(); const s = await createServer();
const aborted = new Promise((resolve, reject) => { const aborted = new Promise((resolve, reject) => {

Loading…
Cancel
Save