Promise Timeout
JS Functions
Medium
15 min
promises
async
timers
Implement promiseTimeout(promise, duration). It returns a new promise that:
- settles the same way as
promiseifpromisesettles withindurationmilliseconds, or - rejects with a timeout error if
durationms pass first.
const fetchUser = () => new Promise((resolve) => setTimeout(() => resolve({ id: 1 }), 50));
await promiseTimeout(fetchUser(), 200); // { id: 1 }
try {
await promiseTimeout(fetchUser(), 10);
} catch (e) {
e instanceof Error; // true
e.name; // 'TimeoutError'
}
Requirements
- The timeout error is an
Errorinstance whosenameis'TimeoutError'. Include the duration in the message. - If
promiserejects in time, the result rejects with the same reason, not a timeout. promisemay also be a plain value or a thenable. Treat it likePromise.resolvewould.- Once the result is settled, later settlement of the input is ignored.
- Clear the timer as soon as the input settles, so it doesn't keep running in the background.
Follow-up
- The wrapped operation keeps running after a timeout. How would you actually cancel it, say for a
fetch? - How would you test this without waiting for real time to pass?
Spotted a mistake or a rights concern? Report an issue