Skip to content

Instantly share code, notes, and snippets.

@positlabs
Last active May 19, 2017 23:27
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 positlabs/91636601b423487175b1cbae11327a85 to your computer and use it in GitHub Desktop.
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.
/*
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