I am writing a constructor in JavaScript that has the following properties:
function WhizBang() {
var promise;
this.publicMethod_One = function publicMethod_One() { ... };
this.publicMethod_Two = function publicMethod_Two() { ... };
promise = asyncInit();
}
So, calling new WhizBang()
will start the asyncInit()
process. What isn't obvious from the code above is that none of the public methods in the interface should run until this call to asyncInit()
has closed.
So, the definition of publicMethod_One()
might look something like this:
function publicMethod_One() {
promise
.then( doStuff )
.catch( reportInitFailure )
;
function doStuff() { ... }
function reportInitFailure() { ... }
}
Some of the things that happen in doStuff()
are asynchronous; some of them aren't.
So, if an end user of my class did something like this:
function main() {
var whizBang = new WhizBang();
whizBang
.publicMethod_One()
.publicMethod_Two()
;
}
The call to publicMethod_One()
musn't be made until asyncInit()
has closed. And the call to publicMethod_Two()
musn't be made until both asyncInit()
and publicMethod_One()
have closed.
How can I define my class methods so that they are chainable?
What I think I need to do is define a class whose public methods are all equivalent to calling then()
on a promise, followed by class specific, implementation stuff.
Internets, halp!
( Bonus points for using the Bluebird Promise Library in your answer. )