Skip to content

Commit 912c2e5

Browse files
committedDec 14, 2019
Emit timeout errors as soon as possible
Fixes #997
1 parent 0569d45 commit 912c2e5

File tree

2 files changed

+14
-11
lines changed

2 files changed

+14
-11
lines changed
 

‎source/utils/timed-out.ts

+1-10
Original file line numberDiff line numberDiff line change
@@ -33,21 +33,12 @@ export default (request: ClientRequest, delays: Delays, options: TimedOutOptions
3333
const {once, unhandleAll} = unhandler();
3434

3535
const addTimeout = <T extends any[]>(delay: number, callback: (delay: number, ...args: T) => void, ...args: T): (typeof noop) => {
36-
// Event loop order is timers, poll, immediates.
37-
// The timed event may emit during the current tick poll phase, so
38-
// defer calling the handler until the poll phase completes.
39-
let immediate: NodeJS.Immediate;
40-
const timeout: NodeJS.Timeout = setTimeout(() => {
41-
// @ts-ignore https://github.com/microsoft/TypeScript/issues/26113
42-
immediate = setImmediate(callback, delay, ...args);
43-
immediate.unref?.();
44-
}, delay);
36+
const timeout = setTimeout(callback, delay, ...args) as unknown as NodeJS.Timeout;
4537

4638
timeout.unref?.();
4739

4840
const cancel = (): void => {
4941
clearTimeout(timeout);
50-
clearImmediate(immediate);
5142
};
5243

5344
cancelers.push(cancel);

‎test/timeout.ts

+13-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import delay = require('delay');
1010
import CacheableLookup from 'cacheable-lookup';
1111
import {Handler} from 'express';
1212
import pEvent = require('p-event');
13-
import got from '../source';
13+
import got, {TimeoutError} from '../source';
1414
import timedOut from '../source/utils/timed-out';
1515
import slowDataStream from './helpers/slow-data-stream';
1616
import {GlobalClock} from './helpers/types';
@@ -622,3 +622,15 @@ test.serial('cancelling the request removes timeouts', withServer, async (t, ser
622622

623623
await delay(1000);
624624
});
625+
626+
test('timeouts are emitted ASAP', async t => {
627+
const timeout = 500;
628+
const marginOfError = 100;
629+
630+
const error: TimeoutError = await t.throwsAsync(got('http://192.0.2.1/test', {
631+
retry: 0,
632+
timeout
633+
}), TimeoutError);
634+
635+
t.true(error.timings.phases.total! < (timeout + marginOfError));
636+
});

2 commit comments

Comments
 (2)

kibertoad commented on Dec 19, 2019

@kibertoad

@sindresorhus Any estimates on when version with this fix will be released?

Please sign in to comment.