I have an object (foo
) that exposes several methods as promises (using jQuery deferred). The way I did it ended up with this kind of code:
var f
Create your own promise.
function MyPromise(resolver) {
var _promise = new Promise(resolver);
this.then = function(onFulfilled, onRejected) {
var _p = _promise.then(onFulfilled, onRejected);
return new MyPromise(_p.then.bind(_p));
};
}
Add whatever methods you want...
MyPromise.prototype.doSomething = function() {
return this.then(/*...*/);
};
voila!
new MyPromise()
.then(/*...*/).doSomething()
.then(/*...*/).doSomething(); // etc...
Bonus:
['resolve', 'reject', 'all'].forEach(function(method) {
MyPromise[method] = function(...args) {
var promise = Promise[method](...args);
return new MyPromise(promise.then.bind(promise));
};
});
Also in ES6:
class MyPromise {
constructor(resolver) {
var _promise = new Promise(resolver);
this.then = function(onFulfilled, onRejected) {
var _p = _promise.then(onFulfilled, onRejected);
return new MyPromise(_p.then.bind(_p));
};
}
doSomething() {
return this.then(/*...*/);
}
}