JavaScript Async - Promises, The Revealing Constructor Pattern |
Written by Ian Elliot | |||
Monday, 11 December 2017 | |||
Page 2 of 2
The Promise MechanismWhen 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. For example, the delay function example introduced in the previous chapter can be written using JavaScript Promises as:
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.
Summary
Now Available as a Book:JavaScript AsyncYou can buy it from: Amazon Contents
To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info <ASIN:1871962528> <ASIN:1871962501> |
|||
Last Updated ( Monday, 11 December 2017 ) |