Created
January 7, 2023 09:05
-
-
Save neharkarvishal/934dddbdd5743f5b80f98cd2ee2fb4c1 to your computer and use it in GitHub Desktop.
Reject promise after timeout
This file contains hidden or 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
/** | |
* 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