Skip to content

Instantly share code, notes, and snippets.

@scothis
Last active December 20, 2015 04:49
Show Gist options
  • Save scothis/6073664 to your computer and use it in GitHub Desktop.
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
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