Created
June 15, 2020 06:14
-
-
Save jonathanrodriguezs/f9d157730669bb03c0d58dca7f015e15 to your computer and use it in GitHub Desktop.
Set a timeout in ms to resolve a promise
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 timeout(ms, promise) { | |
let timeoutID; | |
const timeoutPromise = new Promise((_, reject) => { | |
timeoutID = setTimeout(() => { | |
reject(Error(`Operation timed out after ${ms}ms`)) | |
}, ms) | |
}) | |
return Promise | |
.race([promise, timeoutPromise]) | |
.finally(() => { | |
clearTimeout(timeoutID) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment