Promise with Timeout
MediumUtility Functions15 min4 tests
Implement a withTimeout function that wraps a promise with a timeout. If the promise doesn't resolve within the specified time, reject with a "Timeout" error message.
Requirements
- Accept a promise and a timeout in milliseconds
- If the promise resolves before the timeout, return its value
- If the timeout expires first, reject with the string
"Timeout" - Clean up the timer when the promise resolves to avoid memory leaks
Example
await withTimeout(fetch('/api'), 5000); // Rejects with "Timeout" after 5s
await withTimeout(Promise.resolve(42), 1000); // Resolves with 42Hints (4)
- Use Promise.race to race the original promise against a timeout promise.
- Create a new promise that rejects after the specified milliseconds.
- Use setTimeout inside the timeout promise.
- Clear the timeout when the original promise resolves to prevent leaks.
Topics
- Utility Functions
Asked at
Google · Meta · Netflix · Uber
