Skip to content

Instantly share code, notes, and snippets.

@TooTallNate
Created March 29, 2016 20:50
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 TooTallNate/2dd9945824cc8ca7118e3b9e6e79a0a7 to your computer and use it in GitHub Desktop.
Save TooTallNate/2dd9945824cc8ca7118e3b9e6e79a0a7 to your computer and use it in GitHub Desktop.
LazyPromise implementation. Doesn't invoke the executor function until `.then()` is called.
'use strict';
const Lazy = require('./lazy-promise');
class TimerPromise extends Lazy(Promise) {
constructor() {
const start = new Date();
super((resolve, reject) => resolve(new Date() - start));
}
}
var timer = new TimerPromise();
console.log('created lazy timer promise');
setTimeout(() => timer.then((ms) => {
console.log('%d ms elapsed before executor was called', ms)
}), 2000);
'use strict';
const $executor = Symbol('Lazy#executor');
const $promise = Symbol('Lazy#promise');
const inherits = require('util').inherits;
function Lazy (Promise) {
function LazyPromise(fn) {
if (this[$promise]) {
throw new Error('LazyPromise is already being resolved');
}
this[$executor] = fn;
this[$promise] = null;
// we intentionally do not call `Promise.call(this, fn)` here,
// hence ES6 Classes cannot be used here since `super()` is required there
}
inherits(LazyPromise, Promise);
LazyPromise.prototype.then = function then (resolve, reject) {
var promise = this[$promise];
if (!promise) promise = this[$promise] = new Promise(this[$executor]);
return promise.then(resolve, reject);
};
return LazyPromise;
};
module.exports = Lazy;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment