Advanced promise subclass

by Erik Koopmans

HTML

<h1>Advanced Promise Subclass</h1>
<p>Further improvements over <a href="https://jsfiddle.net/eKoopmans/fuznLccq/2/">basic subclass</a>:</p>
<ol>
  <li>Adds a constructor argument that is stored as a property</li>
  <li>Preserves object properties on chained thens</li>
  <li>Binds `this` in thens to the object, for easy access</li>
  <li>Adds a `.test` method for more chaining fun</li>
</ol>
<p>Check your console for demo messages.</p>

JavaScript

/* --- Advanced Promise Subclass --- */

var PromiseSubclass = function PromiseSubclass(arg) {
    var self = PromiseSubclass.convert(Promise.resolve());
    self.arg = arg;
    return self;
};
PromiseSubclass.convert = function convert(promise, props) {
    promise.__proto__ = PromiseSubclass.prototype;
    return props ? Object.assign(promise, props) : promise;
};
PromiseSubclass.prototype = Object.create(Promise.prototype);
PromiseSubclass.prototype.constructor = PromiseSubclass;
PromiseSubclass.prototype.then = function then(resolve, reject) {
    if (resolve)  { resolve = resolve.bind(this); }
    if (reject)   { reject = reject.bind(this); }
    var returnVal = Promise.prototype.then.call(this, resolve, reject);
    return PromiseSubclass.convert(returnVal, this);
};
PromiseSubclass.prototype.test = function test() {
    console.log('test queued');
    return this.then(function() {
        console.log('test executed');
    });
};

/* --- Demo --- */

function demoFun(msg) {
	return function() {
  	console.log(msg);
  }
}

var demo = new PromiseSubclass(5);
// Chaining thens and custom methods.
demo = demo.test().then(demoFun('then1')).then(demoFun('then2')).test().then(demoFun('then3'));
// Accessing the object via `this` within a then.
demo.then(function() {console.log('Original constructor argument: ' + this.arg);});