Skip to content

Instantly share code, notes, and snippets.

@domenic
Last active August 7, 2017 16:38
Show Gist options
  • Save domenic/6970837 to your computer and use it in GitHub Desktop.
Save domenic/6970837 to your computer and use it in GitHub Desktop.
Promise subclass
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.
});
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));
@kornelski
Copy link

TypeError: #<InstrumentedPromise> is not a promise

Sad panda :(

$ iojs -v
v1.1.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment