I'm reading the Async & Performance book of the YDKJS series and am having trouble wrapping my head around the revealing constructor pattern.
Here's the example the book gives:
function foo(x) {
// start doing something that could take a while
// construct and return a promise
return new Promise( function(resolve,reject){
// eventually, call `resolve(..)` or `reject(..)`,
// which are the resolution callbacks for
// the promise.
} );
}
var p = foo( 42 );
function bar(fooPromise) {
// listen for `foo(..)` to complete
fooPromise.then(
function(){
// `foo(..)` has now finished, so
// do `bar(..)`'s task
},
function(){
// oops, something went wrong in `foo(..)`
}
);
}
bar( p );
I have two questions:
I think the intention is not to expose the resolve and reject logic to the outside, which creates a good separation of concern between the promise logic and what happens next with
.then()
in the function (in this casebar()
) that "listens" to the Promise. Am I on track here?The example
foo()
confuses me. In the comment// start doing something that could take a while
, what exactly is this? Is this where your async call would be? Shouldn't it be inside the function in the return statement? I don't understand how this would work otherwise.