<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Tim Conroy</title>
    <description>The latest articles on DEV Community by Tim Conroy (@timconroy).</description>
    <link>https://dev.to/timconroy</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F302412%2F3e692fdf-404d-46f1-9edb-d5419bd08a90.jpg</url>
      <title>DEV Community: Tim Conroy</title>
      <link>https://dev.to/timconroy</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/timconroy"/>
    <language>en</language>
    <item>
      <title>The JavaScript Promise | Simplified </title>
      <dc:creator>Tim Conroy</dc:creator>
      <pubDate>Tue, 31 Dec 2019 03:27:02 +0000</pubDate>
      <link>https://dev.to/timconroy/promises-resolved-1bh0</link>
      <guid>https://dev.to/timconroy/promises-resolved-1bh0</guid>
      <description>&lt;h2&gt;
  
  
  What is the JavaScript Promise?
&lt;/h2&gt;

&lt;p&gt;Let's start at the base level.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;   1. The top-level "&lt;strong&gt;[Promise]&lt;/strong&gt;" is a JS built-in (native) object.&lt;/li&gt;
&lt;li&gt;   2. It is a '&lt;em&gt;constructor function&lt;/em&gt;' which, like most objects in JS, has a 
    &lt;strong&gt;prototype&lt;/strong&gt; (object) &lt;strong&gt;property&lt;/strong&gt; on it which points to an object. This 
    object contains a "template" or "bucket" of properties and 
    values(key/value pairs). One of those properties is a &lt;strong&gt;constructor&lt;/strong&gt; 
    whose value references the Promise constructor 'function' itself.  The 
    Promise's prototype object &lt;strong&gt;(Promise.prototype)&lt;/strong&gt; can be 
    accessed/referenced by newly created &lt;em&gt;instance&lt;/em&gt;(child)&lt;em&gt;objects&lt;/em&gt; of the 
    parent object, Promise. &lt;/li&gt;
&lt;li&gt;    3. The JavaScript Promise allows one to handle asynchronous operations in 
     an otherwise synchronous, single-threaded(top-down), and non-blocking 
     environment.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Putting it all together: A Promise is an object, which is a constructor function, that acts like a wrapper around other functions, whose purpose is to 'promise' a return value not yet known, in an asynchronous environment. &lt;/p&gt;

&lt;h2&gt;
  
  
  A Promise has three states:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;   1. Pending: The inital state, it's neither fulfilled, nor rejected.&lt;/li&gt;
&lt;li&gt;   2. Fulfilled: Successful.&lt;/li&gt;
&lt;li&gt;   3. Rejected: meaning that the operation failed. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The JS Promise syntax:  &lt;strong&gt;Promise(executor)&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;When a 'new Promise()' is invoked by the JS Engine, it creates a new Promise{} object, and the '&lt;em&gt;executor&lt;/em&gt;' is run &lt;strong&gt;automatically&lt;/strong&gt;. The executor has two arguments which are '&lt;strong&gt;resolve&lt;/strong&gt;' and '&lt;strong&gt;reject&lt;/strong&gt;'. These are &lt;em&gt;callback&lt;/em&gt; &lt;em&gt;functions&lt;/em&gt;. The executor function &lt;strong&gt;first does it's job and obtains the result, be it sooner or later, it then calls on one of these callbacks depending on the executors' result.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The '&lt;em&gt;executor&lt;/em&gt;' is a function which takes two arguments, it's parameters are;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Parameter one: '&lt;strong&gt;resolve&lt;/strong&gt;'
resolve(value)  : value is either (1) &lt;em&gt;state&lt;/em&gt;: fulfilled, or (2)&lt;em&gt;result&lt;/em&gt;: value.&lt;/li&gt;
&lt;li&gt;Parameter two: '&lt;strong&gt;reject&lt;/strong&gt;'
reject(error)   : &lt;em&gt;state&lt;/em&gt;: 'rejected', or &lt;em&gt;result&lt;/em&gt;: error.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The ES5 function declaration:&lt;br&gt;&lt;br&gt;
    &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Promise(function(resolve,reject){};&lt;/code&gt;&lt;/pre&gt;
&lt;br&gt;
The ES6 Arrow Function declaration:&lt;br&gt;
    &lt;pre&gt;&lt;code&gt;Promise((resolve,reject) =&amp;gt; {&lt;br&gt;
               resolve( //resolve someThing placed in here. );&lt;br&gt;
               reject(// if not resolved; do this.);&lt;br&gt;
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;em&gt;'executor function'&lt;/em&gt; is invoked &lt;strong&gt;immediately&lt;/strong&gt; even before the 'Promise' constructor returns the instance object. (This is a [Promise] built-in functionality)&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The parameter's '&lt;em&gt;resolve&lt;/em&gt;' and '&lt;em&gt;reject&lt;/em&gt;' are ordered inside the parentheses. So, the &lt;strong&gt;first parameter&lt;/strong&gt; tests for 'truthy'. And, the &lt;strong&gt;second parameter&lt;/strong&gt; tests for 'falsy'. &lt;/p&gt;

&lt;p&gt;The parameters can be changed to any wording you like; however, conventional useage is encouraged by using 'resolve' and 'reject'. &lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;
  
  
  The constructor syntax for creating a new promise object.
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;   1. Create a variable using either the &lt;strong&gt;let&lt;/strong&gt; or &lt;strong&gt;const&lt;/strong&gt; statement which 
 declares a block-scoped variable. The difference in the two keywords is that 
 the 'value' of &lt;strong&gt;const&lt;/strong&gt; cannot be changed or re-declared. The &lt;em&gt;const&lt;/em&gt; value     can however be 'mutated. This can be rectified by using the ES6 Object.freeze() method.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 5;  //globally scoped

    function foo(){
        let x = 'I am x!, scoped local to this block';  //locally scoped
        console.log(x);  // 'I am x!, scoped local to this block'
     };
console.log(x) // 5
foo();  // 'I am x!, scoped local to this block'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;   2. Using '&lt;em&gt;new Promise()&lt;/em&gt;' creates an instance object of the 
    [Promise] object.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;a. The &lt;strong&gt;new&lt;/strong&gt; operator will create a blank object: Promise{}.&lt;br&gt;
   b. It links up(sets) the constructor of one object &lt;br&gt;
        (Promise.prototype.&lt;strong&gt;constructor&lt;/strong&gt;) to another &lt;br&gt;
        object's constructor(the newly created instance object (&lt;em&gt;p&lt;/em&gt;) of Promise; &lt;br&gt;
        &lt;em&gt;p&lt;/em&gt;. __ proto __.&lt;strong&gt;constructor&lt;/strong&gt;.) &lt;br&gt;
   c. It passes the newly created object (&lt;strong&gt;Promise {}&lt;/strong&gt;) as the &lt;strong&gt;'this'&lt;/strong&gt; &lt;br&gt;
        context. For instance when creating(defining) properties in the &lt;br&gt;
        constructor function Promise's code block, we use the &lt;strong&gt;this&lt;/strong&gt; keyword to&lt;br&gt;
        point to the parent object 'Promise' as we instantiate the property &lt;br&gt;
        members.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;   3. The constructor function &lt;strong&gt;Promise&lt;/strong&gt; and, &lt;em&gt;resolve&lt;/em&gt; and &lt;em&gt;reject&lt;/em&gt;.
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A simplified use of a Promise for the purpose of explaining the resolve and reject methods (functions).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let p1 = new Promise((resolve, reject) =&amp;gt; {

         //set x to the sum of two numbers.
          let x = 10 + 5;

         //if statement and strict equality operator
           if(x === 15) {
                resolve('x is 15');
           }else{
                reject('error: x is not 15')
           }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;ol&gt;
&lt;li&gt;Now we 'use' the newly created instance (child) object, &lt;em&gt;p1&lt;/em&gt;.
We use the Promise.prototype.&lt;strong&gt;then()&lt;/strong&gt; method(function) to return a 
[Promise]. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The '&lt;strong&gt;.then()&lt;/strong&gt; method takes up to two arguments that are 'callback &lt;br&gt;
  functions' for resolve(success) or the rejected(failure) methods.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;The MDN syntax for the Promise.prototype.then() method is;&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;p.then(onFulFilled [, onRejected]);

p.then(value =&amp;gt; {
    // fulfillment
}, reason =&amp;gt; {
    // rejection
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Using an 'asynchronous' operation with a new promise.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let p2 = new Promise((resolve, reject) =&amp;gt; { 

    //creating a 'asyn' condition for test purposes
    setTimeout(() =&amp;gt; {
        resolve('I have been resolved!');
        reject('Failed.');
     }, 3000)  //3000 milliseconds or 3 seconds
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Now, let's test it!&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;p2.then((val) =&amp;gt; {
  console.log(val)   
},(error) =&amp;gt; {
  console.log(error);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When the code is invoked there is a lot initially going on under the hood, but I want to try to keep my explanation short for the code snippet above.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The let variable 'p2' is placed in global memory by the JS engine.&lt;/li&gt;
&lt;li&gt;The JS engine continues to parse the same line of code and sets the 'constructor function' identifier(name) &lt;strong&gt;'Promise'&lt;/strong&gt; with 'new' in global memory and as a copy with it's function definition and it's two parameters, resolve and reject. 
(The engine does not do anything but record the inner function definition, the &lt;strong&gt;setTimeout()&lt;/strong&gt; method.)&lt;/li&gt;
&lt;li&gt;The JS engine next reads the 'p2' and trys to find it. It does. Then the JS engine sees the assignment operator (=) and knows that there is a right-operand. It continues on parsing the right operand; the &lt;strong&gt;new Promise()&lt;/strong&gt;. It finds 'Promise' in it's global memory. The parentheses after the 'Promise' inform the JS engine to invoke(execute/run) the Promise(executor)function. The 'executor' function first does it's job,then based on the result, calls one of the callback function's; either resolve and reject. &lt;/li&gt;
&lt;li&gt;When the inner function, 'setTimeout' is invoked, the JS engine creates a whole new '&lt;em&gt;execution context&lt;/em&gt;' for the function. And, the function gets placed on the call-stack on top of the &lt;em&gt;Promise()&lt;/em&gt; function, and others if still pending. 
(Sorry, I don't have room for explaining the heap, stack, WebAPI'S, event loop, or the callback queue. All important topics on their own).
&lt;/li&gt;
&lt;li&gt;Once a promise is fulfilled or rejected the appropriate handler, either the 'onFulFilled' or the 'onRejected' will run 'asynchronously'.&lt;/li&gt;
&lt;li&gt;The 'then()' method basically says, 'return my promise'. &lt;/li&gt;
&lt;li&gt;The 'then()' method is also used for method chaining. (To be covered in my next post)&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;We can also use the 'catch()' method of the parent object: [Promise].&lt;br&gt;
Instance objects have access to the properties and methods on the parent object - Promise, through the prototype-chain. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Thank you for taking time out to read my post. I am a self-taught web developer. So, when you find my mistakes...please inform so that I can correct and better yet...continue to learn from them.&lt;/p&gt;

&lt;p&gt;TC&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
