Created
September 27, 2015 02:38
-
-
Save okorz001/68429aa70e91a1ee31f9 to your computer and use it in GitHub Desktop.
Run a JS promise exactly once
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
// Sentinel value that indicates Promise has not executed. | |
var empty = {}; | |
function once(f) { | |
var result = empty; | |
var promise = null; | |
return function() { | |
// If we've saved something already, resolve it immediately. | |
if (result !== empty) { | |
return Promise.resolve(result); | |
} | |
if (promise == null) { | |
// Create the promise and save the result afterwards. | |
promise = f(); | |
promise.then(function(result_) { result = result_; }); | |
} | |
// Return the promise so clients can wait on it. | |
return promise; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment