Created
March 29, 2016 20:50
-
-
Save TooTallNate/2dd9945824cc8ca7118e3b9e6e79a0a7 to your computer and use it in GitHub Desktop.
LazyPromise implementation. Doesn't invoke the executor function until `.then()` is called.
This file contains 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
'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); |
This file contains 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
'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