Last active
December 20, 2015 04:49
-
-
Save scothis/6073664 to your computer and use it in GitHub Desktop.
Creates a lazy promise that only starts its work once there is interest in the outcome
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
var when = require('when'), | |
whenFn = require('when/function'); | |
function lazyPromise(work) { | |
var defer, started, resolver, promise, then; | |
defer = when.defer(); | |
started = false; | |
resolver = defer.resolver; | |
promise = defer.promise; | |
then = promise.then; | |
promise.then = function () { | |
if (!started) { | |
started = true; | |
whenFn.apply(work).then(resolver.resolve, resolver.reject); | |
} | |
return then.apply(promise, arguments); | |
}; | |
return promise; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment