Created
August 22, 2018 02:32
-
-
Save noyobo/863255146456e7ceb825b4ae905e401d to your computer and use it in GitHub Desktop.
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
const FETCH_TIMEOUT = 5000; | |
let didTimeOut = false; | |
new Promise(function(resolve, reject) { | |
const timeout = setTimeout(function() { | |
didTimeOut = true; | |
reject(new Error('Request timed out')); | |
}, FETCH_TIMEOUT); | |
fetch('https://davidwalsh.name/?xx1') | |
.then(function(response) { | |
// Clear the timeout as cleanup | |
clearTimeout(timeout); | |
if(!didTimeOut) { | |
console.log('fetch good! ', response); | |
resolve(response); | |
} | |
}) | |
.catch(function(err) { | |
console.log('fetch failed! ', err); | |
// Rejection already happened with setTimeout | |
if(didTimeOut) return; | |
// Reject with error | |
reject(err); | |
}); | |
}) | |
.then(function() { | |
// Request success and no timeout | |
console.log('good promise, no timeout! '); | |
}) | |
.catch(function(err) { | |
// Error: response error, request timeout or runtime error | |
console.log('promise error! ', err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment