Skip to content

Instantly share code, notes, and snippets.

@cladley
Last active June 29, 2016 09:25
Show Gist options
  • Select an option

  • Save cladley/98f7de09ac09916692aa6fd745d583ca to your computer and use it in GitHub Desktop.

Select an option

Save cladley/98f7de09ac09916692aa6fd745d583ca to your computer and use it in GitHub Desktop.
/**
* Timeout promise that can cancel a long running promise
* using Promise.race
*/
function timeoutPromise(delay) {
return new Promise(function(resolve, reject) {
setTimeout(function(){
reject("Timeout!");
}, delay);
});
}
/* Whatever wins in the race, cancels others */
Promise.race([
longRunningFunction(),
timeoutPromise(4000)
]).then(function(result){
console.log(result);
}).catch(function(err){
/* Time out */
console.log(err);
});
/**
* Delay promise that delays resolving
*/
function delay(time) {
return new Promise(function(resolve, reject) {
setTimeout(resolve, time);
});
}
delay(3000)
.then(function(){
// Do something
})
.then(someOtherFunction())
.catch(function(err){ /* <-- Should always put a catch at end of a chain of promises to catch any errors */
console.log(err); /* as they will be swollowed otherwise */
});
/**
* Example that uses Promise.all to fetch x amount of webpages
* and getting total length of them.
*/
function fetch(url) {
/* Returns a promise */
return requestPromise(url);
}
function addAll(...prms) {
/* Promise.all takes a mixed array or promises
and non promises. Its wraps the non promises in
a promise */
return Promise.all(prms).then(function(htmls){
return htmls.reduce((prev, current) => {
return current.length + prev;
}, 0);
});
}
function getTotal(...urls) {
var prms = urls.map((url) => {
return fetch(url);
});
return addAll(...prms);
}
/* Usage */
getTotal('http://www.google.com', 'http://www.reddit.com', 'http://www.arstechnica.com')
.then(function(total){
console.log(total);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment