Skip to content

Instantly share code, notes, and snippets.

@willywongi
Created March 25, 2015 10:48
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 willywongi/5bc908272ee066a4bf77 to your computer and use it in GitHub Desktop.
Save willywongi/5bc908272ee066a4bf77 to your computer and use it in GitHub Desktop.
Function returning the same promise as long it's not fullfilled/rejected.
function getSomething() {
/**
* Returns a promise that fullfills in 15 seconds
**/
if (getSomething._promise) {
return getSomething._promise;
} else {
return getSomething._promise = new Promise(function(resolve, reject) {
setTimeout(function() {
getSomething._promise = null;
resolve('something');
}, 15000);
});
}
}
/*
Running getSomething more than once before its fullfilment returns the same promise.
Useful if you don't want to run a XHR call more than once.
*/
var p1 = getSomething();
var p2 = getSomething();
/* p1 === p2 */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment