Last active
January 1, 2019 02:02
-
-
Save justsml/5e492db8997a4f7e22e61b7486cbf273 to your computer and use it in GitHub Desktop.
adds tracking of the promise timeout via `__timeout` flag
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 promiseTimeout(msec) { | |
return (promise) => { | |
let isDone = false | |
promise.then(() => isDone = true) | |
const timeout = new Promise((yea, nah) => setTimeout(() => { | |
if (!isDone) { | |
promise.__timeout = true | |
nah(new Error('Timeout expired')) | |
} | |
}, msec)) | |
return Promise.race([promise, timeout]) | |
} | |
} | |
promiseTimeout(5000)(fetch('https://api.github.com/orgs/nodejs')) | |
.then(response => response.json()) | |
.then(data => { | |
console.log(data) // Prints result from `response.json()` in getRequest | |
}) | |
.catch(error => console.error(error)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment