JSFiddle - React, Tailwind, and code Playground

by Erik Koopmans

HTML

<h1>Basic Promise Subclass</h1>
<p>Improvements over <a href="https://gist.github.com/domenic/8ed6048b187ee8f2ec75">existing method</a>:</p>
<ol>
  <li>Doesn't require a function input in the constructor</li>
  <li>Preserves object type on chained thens</li>
</ol>
<p>Further improvements can be found in <a href="https://jsfiddle.net/eKoopmans/nquopqxp/">Advanced Promise Subclass</a>.</p>
<p>Check your console for demo messages.</p>

JavaScript

/* --- Basic Promise Subclass --- */

var PromiseSubclass = function PromiseSubclass() {
    var self = PromiseSubclass.convert(Promise.resolve());
    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) {
    var returnVal = Promise.prototype.then.call(this, resolve, reject);
    return PromiseSubclass.convert(returnVal);
};

/* --- Demo --- */

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

var demo = new PromiseSubclass();
demo = demo.then(demoFun('then1')).then(demoFun('then2'));
console.log('Final object type: ' + demo.constructor.name);