Skip to content

Instantly share code, notes, and snippets.

@noyobo
Created August 22, 2018 02:32
Show Gist options
  • Save noyobo/863255146456e7ceb825b4ae905e401d to your computer and use it in GitHub Desktop.
Save noyobo/863255146456e7ceb825b4ae905e401d to your computer and use it in GitHub Desktop.
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