Skip to content

Instantly share code, notes, and snippets.

@danthareja
Created August 15, 2024 06:43
Show Gist options
  • Save danthareja/7161844b1631ed67590133846973db43 to your computer and use it in GitHub Desktop.
Save danthareja/7161844b1631ed67590133846973db43 to your computer and use it in GitHub Desktop.
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