Skip to content

Instantly share code, notes, and snippets.

@domenic
Created January 21, 2016 23:28
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save domenic/8ed6048b187ee8f2ec75 to your computer and use it in GitHub Desktop.
Save domenic/8ed6048b187ee8f2ec75 to your computer and use it in GitHub Desktop.
How to subclass a promise
// 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;
}
@Heniker
Copy link

Heniker commented Nov 16, 2023

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