Created
January 21, 2016 23:28
-
-
Save domenic/8ed6048b187ee8f2ec75 to your computer and use it in GitHub Desktop.
How to subclass a promise
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
// ES6 | |
class AngularPromise extends Promise { | |
constructor(executor) { | |
super((resolve, reject) => { | |
// before | |
return executor(resolve, reject); | |
}); | |
// after | |
} | |
then(onFulfilled, onRejected) { | |
// before | |
const returnValue = super.then(onFulfilled, onRejected); | |
// after | |
return returnValue; | |
} | |
} | |
// ES5 | |
function AngularPromise(executor) { | |
var p = new Promise(function (resolve, reject) { | |
// before | |
return executor(resolve, reject); | |
}); | |
// after | |
p.__proto__ = AngularPromise.prototype; | |
return p; | |
} | |
AngularPromise.__proto__ = Promise; | |
AngularPromise.prototype.__proto__ = Promise.prototype; | |
AngularPromise.prototype.then = function then(onFulfilled, onRejected) { | |
// before | |
var returnValue = Promise.prototype.then.call(this, onFulfilled, onRejected); | |
// after | |
return returnValue; | |
} |
You don't have to define constructor argument If you don't need the value returned by .then
method to be of your class instance.
Example:
class DeferredPromise extends Promise {
static get [Symbol.species]() {
return Promise;
}
constructor() {
let internalResolve = () => { };
let internalReject = () => { };
super((resolve, reject) => {
internalResolve = resolve;
internalReject = reject;
});
this.resolve = internalResolve;
this.reject = internalReject;
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is what I came up with after a few hours of debugging and trial+error. It stores the call stack of the location where it is instantiated, allowing
rejectWithError()
to produce useful errors even when it is called from a parallel asynchronous process, e.g. an event handler.You can use it like this:
Example use in my own project:
deferred-promise.ts
usage in badge-usb.ts >
BadgeUSB._handlePacket()