Last active
August 7, 2017 16:38
-
-
Save domenic/6970837 to your computer and use it in GitHub Desktop.
Promise subclass
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
class InstrumentedPromise extends Promise { | |
constructor(...args) { | |
super(...args); | |
console.log("constructed"); | |
} | |
then(...args) { | |
console.log("then'd"); | |
return this.constructor.cast(super(...args)); | |
} | |
} | |
var p = Promise.resolve(); | |
var instrumentedP = InstrumentedPromise.resolve(); | |
p.then(() => instrumentedP).then(() => { | |
// By now, "then'd" should have been logged, but under the status quo, it is not. | |
}); |
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
class TransformPromise extends Promise { | |
constructor(resolver, transform) { | |
super(resolver); | |
this._transform = transform; | |
} | |
then(onFulfilled, onRejected) { | |
return this.constructor.cast(super(x => onFulfilled(this._transform(x)), onRejected)); | |
} | |
} | |
var p = Promise.resolve(5); | |
var transformP = new TransformPromise(resolve => resolve(p), x => x + 10); | |
transformP.then(x => console.log(x)); // logs 15 | |
// should log 15, but logs 5 under status quo. | |
Promise.resolve().then(() => transformP).then(x => console.log(x)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sad panda :(