I'm trying to extend the javascript promise with a new method. This new method in this case is called foo
, which really does something like this:
Promise.foo = function(arg) {
return this.then( function(result) {
return result.foo(arg);
});
};
So in short, the foo() function is a shortcut for waiting for a promise to resolve and then calling foo() on the result.
The nature of this function is that it can be chained, just like then()
can.
myPromise.foo(a).foo(b).foo(c);
I feel like this should be possible, but I'm just not sure what the right path is.
This is what I've tried:
var FooPromise = function() {
Promise.apply(this, arguments);
}
FooPromise.prototype = Object.create(Promise.prototype);
FooPromise.foo = function(arg) {
return this.then( function(result) {
return result.foo(arg);
});
};
To test it out:
var test = new FooPromise(function(res, rej) {
res('bla');
});
In firefox this gives me:
TypeError: calling a builtin Promise constructor without new is forbidden
In Node:
TypeError: #<Promise> is not a promise
Is this just a limitation of javascript, or is there a way around this?
After more research, I landed on the following solution. There's no need to extend the built-in Promise. All you really need is to make sure your object implements
then
correctly (aka Promise/A+ / thenable).This works fine in ES5 environments, works perfectly with other promises and even async/await (where available).
I successfully implemented this pattern this open source library.
ES6 way: