<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);});
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.