Skip to content

Instantly share code, notes, and snippets.

@neharkarvishal
Created January 7, 2023 09:05
Show Gist options
  • Save neharkarvishal/934dddbdd5743f5b80f98cd2ee2fb4c1 to your computer and use it in GitHub Desktop.
Save neharkarvishal/934dddbdd5743f5b80f98cd2ee2fb4c1 to your computer and use it in GitHub Desktop.
Reject promise after timeout
/**
* Reject promise after timeout
*
* @todo this is slow, we should find a way to do this in a faster way
* @param {Promise<any>} callback
* @param {number} ms
* @return {Promise<never>}
*/
function withTimeout(callback, ms) {
let timeout;
return Promise.race([
callback().then((result) => {
clearTimeout(timeout);
return result;
}),
new Promise((_, reject) => {
timeout = setTimeout(() => {
reject(new Error('timeout'));
}, ms);
}),
]);
}
module.exports = {
withTimeout,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment