Created
August 15, 2024 06:43
-
-
Save danthareja/7161844b1631ed67590133846973db43 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function withTimeout( | |
asyncFn, | |
timeoutMins = 5 | |
) { | |
return function asyncFnWithTimeout(job) { | |
return new Promise((resolve, reject) => { | |
const timer = setTimeout(() => { | |
return reject(new Error(`Job timed out after ${timeoutMins} minutes`)); | |
}, parseInt(timeoutMins) * 60 * 1000); | |
return asyncFn(job) | |
.then((result) => resolve(result)) | |
.catch((error) => reject(error)) | |
.finally(() => { | |
clearTimeout(timer); | |
}); | |
}); | |
}; | |
} | |
// Usage | |
const asyncFn = async (job) => { | |
// Do something async | |
return job; | |
} | |
async function main() { | |
const asyncFnWithTimeout = withTimeout(asyncFn, 5); | |
try { | |
const result = await asyncFnWithTimeout('Job'); | |
console.log(result); | |
} catch (error) { | |
console.error(error); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment