A utility to add timeout functionality to promises, rejecting or providing a fallback if they take too long.
p-timeout is a Node.js utility library that adds timeout functionality to promises. It solves the problem of promises running indefinitely by allowing developers to set a maximum execution time, after which the promise either rejects with a customizable error or triggers a fallback function. This is particularly useful for managing asynchronous operations that may hang or take too long, such as API calls or long-running tasks.
Node.js developers working with asynchronous code who need to enforce time limits on promises, such as those building servers, CLI tools, or applications with network requests.
Developers choose p-timeout for its simplicity, flexibility, and compatibility with modern standards like `AbortSignal`. It offers fine-grained control over timeout behavior, including fallback functions and custom error handling, without the complexity of manual timeout management.
Timeout a promise after a specified amount of time
Open-Awesome is built by the community, for the community. Submit a project, suggest an awesome list, or help improve the catalog on GitHub.
Allows specifying a fallback function to execute on timeout, enabling retries or alternative logic, as shown in the README example where it retries a delayed promise.
Accepts custom setTimeout and clearTimeout implementations, making it easy to integrate with testing tools like Sinon.useFakeTimers() without interference.
Automatically calls the .cancel() method on cancelable promises when a timeout occurs, facilitating resource cleanup in long-running tasks.
Supports AbortSignal for abortable operations, aligning with web standards and allowing integration with signals from sources like fetch or user actions.
The README explicitly notes that AbortSignal.timeout() is a modern alternative, as it notifies the underlying function to abort, making p-timeout less optimal for new code targeting recent environments.
Primarily designed for Node.js, so using it in browser contexts requires additional setup or polyfills, unlike built-in solutions like AbortSignal.timeout().
While fallback functions enable retries, implementing robust retry logic is manual and cumbersome compared to dedicated libraries like p-retry from the same author.