Created
January 11, 2019 21:59
-
-
Save marioluevanos/938cd6f6985044f04aaf3e66720416de to your computer and use it in GitHub Desktop.
A Promise with a 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
function promiseWithTimeout(promise, timeoutTime = 5000) { | |
return new Promise((resolve, reject) => { | |
const timeout = setTimeout(() => reject({ | |
message: 'timeout' | |
}), timeoutTime) | |
const resolveWithTimeout = (res) => { | |
clearTimeout(timeout) | |
resolve(res) | |
} | |
const rejectWithTimeout = (err) => { | |
clearTimeout(timeout) | |
reject(err) | |
} | |
promise.then(resolveWithTimeout).catch(rejectWithTimeout) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment