Error Handling in Async Code
What error handling best practice is demonstrated?
async function withTimeout(promise, ms, errorMessage) {
let timeoutId;
try {
const timeoutPromise = new Promise((_, reject) => {
timeoutId = setTimeout(() => {
reject(new Error(errorMessage || `Operation timed out after ${ms}ms`));
}, ms);
});
return await Promise.race([promise, timeoutPromise]);
} finally {
clearTimeout(timeoutId);
}
}