Timeout With Promise.race
NodeJS
Hard
4 views
Problem Description
Add a timeout wrapper for an async task using Promise.race.
Output Format
Print TIMEOUT or DONE.
Constraints
Use a task that never resolves.
Official Solution
function withTimeout(promise, ms) {
const timeout = new Promise((resolve) => setTimeout(() => resolve('TIMEOUT'), ms));
return Promise.race([promise.then(() => 'DONE'), timeout]);
}
const never = new Promise(() => {});
withTimeout(never, 40).then((x) => console.log(x));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!