https://github.com/alsiola/with-timeout
Add a timeout to an asynchronous function
https://github.com/alsiola/with-timeout
Last synced: 11 days ago
JSON representation
Add a timeout to an asynchronous function
- Host: GitHub
- URL: https://github.com/alsiola/with-timeout
- Owner: alsiola
- License: mit
- Created: 2018-09-12T21:55:11.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2022-12-09T12:18:27.000Z (over 3 years ago)
- Last Synced: 2025-01-02T20:36:15.005Z (over 1 year ago)
- Language: TypeScript
- Size: 464 KB
- Stars: 0
- Watchers: 3
- Forks: 0
- Open Issues: 16
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# with-timeout
Add a timeout to an asynchronous function.
This package exports a single function, `withTimeout`, an Error class, `TimeoutError, and a guard function that will determine if an error is a TimeoutError.
Given a Promise-returning function, `F1`, where:
`type F1 = (a: T) => Promise;`
and a number of milliseconds in which to timeout, withTimeout returns a new function with the same signature. The returned function will resolve/reject with the original function if the original function resolves/rejects within the timeout. If the timeout expires, the returned function will reject with an instance of `TimeoutError`.
## Example Usage
Add a timeout to a node readFile operation:
```
import { readFile } from "fs";
import { promisify } from "util";
import { withTimeout, isTimeoutError } from "with-timeout";
const TIMEOUT_MS = 1000;
const readFileWithTimeout = withTimeout(promisify(readFile), TIMEOUT_MS);
readFileWithTimeout("./filename.txt")
.then(file => { /* Do something */ })
.catch(err => {
if (isTimeoutError(err)) {
// Read file timed out
} else {
// Read file rejected
}
})
```