<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);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.