Q11: Implement Promise Timeout (Cancel Race)
Wrap a target Promise with a timeout reject mechanism using Promise.race, ensuring the operation fails if it exceeds a specified delay threshold.
Promise Timeout Wrapper
function promiseWithTimeout(promise, ms) {
const timeout = new Promise((_, reject) => {
setTimeout(() => reject(new Error(`Operation timed out after ${ms}ms`)), ms);
});
return Promise.race([promise, timeout]);
}
const slowTask = new Promise(res => setTimeout(() => res('Done'), 2000));
promiseWithTimeout(slowTask, 1000).catch(err => console.error(err.message));Promise.race resolves with the target result if it completes before the setTimeout reject fires.
Key Takeaways
Promise.race resolves or rejects as soon as any promise in the array settles.
Combines target promise against a timer reject promise.
Knowledge Check
If the main promise resolves in 500ms and the timeout is set to 1000ms, what is the output of Promise.race?