Last active
May 19, 2017 23:27
-
-
Save positlabs/91636601b423487175b1cbae11327a85 to your computer and use it in GitHub Desktop.
LazyPromise is a cachey promise creator that returns a function. It's good for lazily running things only once.
This file contains hidden or 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
/* | |
LazyPromise is a cachey promise creator that returns a function. | |
It's good for lazily running things only once. | |
Promise creation is deferred until the first call. | |
Construct using same signature as a regular Promise (except it doesn't require `new`). | |
var lazyp = LazyPromise((resolve, reject) => {}) | |
The first invocation will create the Promise and run the resolver method. | |
lazyp() | |
Subsequent invocations will return the cached Promise. | |
lazyp() | |
lazyp() | |
*/ | |
function _LazyPromise(resolver){ | |
var _promise | |
var runner = (resolve, reject) => { | |
if(!_promise){ | |
_promise = new Promise((resolve, reject) => { | |
resolver(resolve, reject) | |
}) | |
} | |
return _promise | |
} | |
return runner | |
} | |
function LazyPromise(resolver){ | |
return new _LazyPromise(resolver) | |
} | |
module.exports = LazyPromise | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment