Skip to content

Instantly share code, notes, and snippets.

@husa
Last active August 31, 2016 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save husa/b13692cd7bf44e16bba04945eda3da29 to your computer and use it in GitHub Desktop.
Save husa/b13692cd7bf44e16bba04945eda3da29 to your computer and use it in GitHub Desktop.
fetch content with timeout
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