Created
March 25, 2015 10:48
-
-
Save willywongi/5bc908272ee066a4bf77 to your computer and use it in GitHub Desktop.
Function returning the same promise as long it's not fullfilled/rejected.
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
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