JavaScript Async - Promises, The Revealing Constructor Pattern
Written by Ian Elliot   
Monday, 11 December 2017
Article Index
JavaScript Async - Promises, The Revealing Constructor Pattern
The Promise Mechanism

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.

For example, the delay function example introduced in the previous chapter can be written using JavaScript Promises as:

function delay(t) {
  var p = new Promise(
               function (resolve, reject) {
                 setTimeout(
                    function () {
                         resolve();
                     },
                 t);
               });

  return p;
}

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:

function delay(t, p) {
      var promise = new Promise(
                      function (resolve, reject) {
                         setTimeout(
                            function () {
                             var r = Math.random();
                             if (r > p) {
                               resolve(r);
                             } else {
                               reject(r);
                             }
                            },
                         t);
                      });
       return promise;
}

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

 

  • Promises are designed to restrict access to the resolve and reject functions to the code that creates the Promise.

  • This used to be done using a separate deferred object which was kept private.

  • The Promise standard makes use of the revealing constructor pattern to keep resolve and reject private, while allowing the code that creates the Promise to submit to the constructor a function that makes use of them.

  • The revealing constructor pattern extends the way a closure provides private variables and functions to the constructed object by passing private variables to a function that is passed to the constructor.

 

Now Available as a Book:

 JavaScript Async

cover

You can buy it from: Amazon

Contents

  1. Modern JavaScript (Book Only)
  2. Events,Standard & Custom
  3. The Callback
      extract - The Callback & The Controller
  4. Custom Async - setTimeout, sendMessage & yield
      extract - Custom Async
      extract - Avoiding State With Yield 
  5. Worker Threads
      extract - Basic Worker ***NEW
      extract - Advanced Worker Threads 
  6. Consuming Promises 
  7. Producing Promises
      extract - The Revealing Constructor Pattern
     
    extract - Returning Promises
     
    extract - Composing Promises
  8. The Dispatch Queue
      extract - Microtasks
  9. Async & Await
      extract -  Basic Async & Await
      extract -  DoEvents & Microtasks
  10. Fetch, Cache & Service Worker
      extract - Fetch  
      extract - Cache
     
    extract -  Service Workers

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.

espbook

 

Comments




or email your comment to: comments@i-programmer.info

 <ASIN:1871962528>

<ASIN:1871962501>



Last Updated ( Monday, 11 December 2017 )