|Written by Ian Elliot|
|Monday, 11 December 2017|
Page 2 of 2
The Promise Mechanism
When you create a standard Promise you use its constructor and you pass it a function, the executor, that is immediately executed by the constructor. This is the function where you create the asynchronous task and then call resolve or reject accordingly – usually when the asynchronous task has completed.
In other words this is the code that does the work.
You can see that it has the same basic structure, the only difference is that now the code calls the private resolve and reject functions that are defined within the constructor. The constructor executes this immediately, passing it the private resolve and reject functions and returns the Promise.
Notice that within the function that you pass to the constructor, the calls to resolve and reject result in calling all of the onComplete and onError functions that the consumer of the Promise has set up using the then method of the returned Promise object. Only call resolve or reject when the asynchronous task has completed, and return its value or error code in resolve and reject.
Now we are in a position to understand the demonstration Promise introduced in the previous chapter:
You can see that what happens is we create a new Promise object which is returned to the caller almost at once. We also use setTimeout to place a function on the event queue which when its time is up calls either the resolve or the reject function with the specified probability passing the random number back as the resolved value.
To be 100% clear the resolve and reject functions that you use in the Promise constructor are private functions provided by the constructor. The revealing constructor pattern ensures that these cannot be accessed by any other code outside of the constructor or the promise.
Now Available as a Print Book:
You can buy it from: Amazon
or email your comment to: email@example.com
|Last Updated ( Monday, 11 December 2017 )|