Last active
August 31, 2016 09:29
-
-
Save husa/b13692cd7bf44e16bba04945eda3da29 to your computer and use it in GitHub Desktop.
fetch content with timeout
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 MIN_LOADING_TIME = 4000; | |
function fetchContent (url, options) { | |
// fetch from remote or get from cache | |
return fetch(url, options).then(response => response.json()) | |
} | |
function wait(time) { | |
return new Promise(resolve => setTimeout(resolve, time)) | |
} | |
function load(url, options) { | |
return Promise.all([ | |
fetchContent(url, options), | |
wait(MIN_LOADING_TIME) | |
]) | |
.then((...args) => args[0]) | |
.then( | |
data => { | |
// someCustomSuccessCallback(data); | |
return data; | |
}, | |
err => { | |
// someCustomErrorCallback(err); | |
return err; | |
} | |
); | |
} | |
//USAGE | |
const start = +new Date; | |
// load info about current gist | |
load('https://api.github.com/gists/b13692cd7bf44e16bba04945eda3da29') | |
.then(data => console.log(data)) | |
.then(() => { | |
console.log(`Should be no less than ${MIN_LOADING_TIME}: ${+new Date - start}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment