-
Notifications
You must be signed in to change notification settings - Fork 761
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[feat] timeout response, timeout deadline
- Loading branch information
Showing
4 changed files
with
142 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
const makeResponseTimeoutError = function (ms) { | ||
// https://github.com/visionmedia/superagent/blob/master/lib/request-base.js#L666 | ||
const err = new Error(`Response timeout of ${ms}ms exceeded`) | ||
err.code = 'ECONNABORTED' | ||
err.errno = 'ETIMEDOUT' | ||
return err | ||
} | ||
const makeDeadlineTimeoutError = function (ms) { | ||
const err = new Error(`Timeout of ${ms}ms exceeded`) | ||
err.code = 'ECONNABORTED' | ||
err.errno = 'ETIME' | ||
return err | ||
} | ||
|
||
export function responseTimeout(ms, promise) { | ||
return new Promise((resolve, reject) => { | ||
let timerId | ||
if (ms !== undefined) { | ||
timerId = setTimeout(() => { | ||
reject(makeResponseTimeoutError(ms)) | ||
}, ms) | ||
} | ||
promise.then((val) => { | ||
clearTimeout(timerId) | ||
resolve(val) | ||
}, reject) | ||
}) | ||
} | ||
|
||
export function deadlineTimeout(timeStart, timeoutDeadline, promise) { | ||
const timeTtfb = Date.now() | ||
const timeElapsed = (timeTtfb - timeStart) | ||
let ms // remaining ms | ||
if (timeoutDeadline !== undefined) { | ||
ms = timeoutDeadline - timeElapsed | ||
} | ||
return new Promise((resolve, reject) => { | ||
let timerId | ||
if (ms !== undefined) { | ||
if (ms < 0) { | ||
return reject(makeDeadlineTimeoutError(timeoutDeadline)) | ||
} | ||
timerId = setTimeout(() => { | ||
reject(makeDeadlineTimeoutError(timeoutDeadline)) | ||
}, ms) | ||
} | ||
promise.then((val) => { | ||
clearTimeout(timerId) | ||
resolve(val) | ||
}, reject) | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters