Skip to content

Instantly share code, notes, and snippets.

@okorz001
Created September 27, 2015 02:38
Show Gist options
  • Save okorz001/68429aa70e91a1ee31f9 to your computer and use it in GitHub Desktop.
Save okorz001/68429aa70e91a1ee31f9 to your computer and use it in GitHub Desktop.
Run a JS promise exactly once
// 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