JavaScript Promises Explained
Published: 2020-06-02 03:59:56

<!-- wp:paragraph -->
<p>In this tutorial, you will learn about JavaScript promises, what are promises and how to use them. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Imagine that you have a car(🚗) shop. Where cars (🚗🚗🚗) are repaired.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>And a customer (<strong>💁</strong>) brings his car (🚗) to your repair shop. And says that my car has to be repaired. It has some problems.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Promise you that your car (🚗) will be repaired till evening today. Here you promise the customer. But three states are formed in it. Given below states of promise:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>When the car(🚗) came to your repair center, it was in the pending state.</li><li>If you repair the car(🚗) till today evening. So your promise is resolved.</li><li>If the problem of the car(🚗) is not solved today evening, then it comes to the reject state.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Let us now explain to you the promises of JavaScript.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Intro - Promises in JavaScript</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In JavaScript, a promise is an object that contains the future value of an asynchronous operation. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Sometimes, when you work with webservers and requesting some data from a webserver, the javascript promise promises us to get data from webserver and you can use in the future.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>States of a Promise</h3>
<!-- /wp:heading -->

<!-- wp:image {"id":8671,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://www.tutsmake.com/wp-content/uploads/2020/05/javascript-promises-states.jpeg" alt="javascript promises states" class="wp-image-8671"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>A promise has three states:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Pending:  first of all, the job is in a pending state. </li><li>Fulfilled:  A Promise is resolved if the job finished successfully. </li><li>Rejected:  A Promise is rejected if the job an error occurred. </li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Note that, A promise begins in the pending state which indicates that the promise hasn’t completed. It finishes with either a successful or failed state.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 id="bf7d">Creating a Promise</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>You can see the following syntax for how to create promises using  <code>Promise</code>&nbsp;constructor.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4 id="a34c">The constructor syntax for a promise object is:</h4>
<!-- /wp:heading -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">let promise = new Promise((resolve, reject) =&gt; {     ...   });</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>To create a promise in JavaScript, you use the&nbsp;<code>Promise</code>&nbsp;constructor, <code>new Promise</code>&nbsp; the executor and it runs automatically. It contains the producing code which should eventually produce the result. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The promise is resolved by calling the&nbsp;<code>resolve()</code>&nbsp;and rejected by calling&nbsp;<code>reject()</code>. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>See the following example:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code {"language":"jscript"} -->
<pre class="wp-block-syntaxhighlighter-code">let finish = true;

let res = new Promise(function (resolve, reject) {
    if (finish) {
        resolve("Your 🚗 has repaired.");
    } else {
        reject("Your 🚗 has not repaired yet.");
    }
});
</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>The&nbsp;Promise constructor takes a <a href="https://www.tutsmake.com/javascript-function-with-example/">function</a> as an argument and this function takes two functions <code>resolve()</code>&nbsp;and&nbsp;<code>reject()</code>.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>When you call the&nbsp;<code>new Promise(executor)</code>, the&nbsp;<code>executor</code>&nbsp;is called automatically.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>According to job state, inside the executor(new promise), you can call&nbsp;<code>resolve()</code>&nbsp;and <code>reject()</code>&nbsp;function,  if completed job successfully then call  <code>resolve()</code>&nbsp; and if job failed then <code>reject()</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>See the following example:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code {"language":"jscript"} -->
<pre class="wp-block-syntaxhighlighter-code">let finish = true;

let res = new Promise(function (resolve, reject) {
    setTimeout(() => {
        if (finish) {
            resolve("Your 🚗 has repaired.");
        } else {
            reject("Your 🚗 has not repaired yet.");
        }
    }, 5 * 1000);
});
console.log(res);</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>Now, you see that the promise begins with the&nbsp;<code>pending</code>&nbsp;state with the value is&nbsp;<code>undefined</code>. The promise value will be returned later once the promise is fulfilled.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":8672,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://www.tutsmake.com/wp-content/uploads/2020/05/JavaScript-Promise-Pending-state.png" alt="" class="wp-image-8672"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>After the 5 seconds timer finishes, the promise is either resolved or rejected randomly, and its value will be the value passed to the resolve or reject function. See the following:</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":8674,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://www.tutsmake.com/wp-content/uploads/2020/05/javascript-promise-resolved-state-1.png" alt="" class="wp-image-8674"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>That was an example of a job resolved.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":8675,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://www.tutsmake.com/wp-content/uploads/2020/05/promise-resolved-state.jpeg" alt="" class="wp-image-8675"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>After that, If you change the value of the&nbsp;<code>finish</code>&nbsp;variable and it value to <code>false</code>&nbsp;and run the script again:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code -->
<pre class="wp-block-syntaxhighlighter-code">let finish = false;</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>Note that, this time Calling&nbsp;<code>reject()</code> state and display error message&nbsp;after 5 seconds.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> That was an example of a job rejected. </p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":8676,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://www.tutsmake.com/wp-content/uploads/2020/05/promise-rejected-state.jpeg" alt="" class="wp-image-8676"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>When you create a  <code>Promise</code>&nbsp;<a href="https://www.tutsmake.com/javascript-objects/">object</a> using  <code> new Promise</code>&nbsp;, this time is in pending state until it is not fulfilled state (resolved or rejected).</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Consuming a Promise</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>You can consume promise by calling&nbsp;<code>then()</code>, <code>catch()</code>&nbsp;and  , <code>finally()</code> methods on the promise. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>1) The&nbsp;<code>then()</code>&nbsp;method</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p> The&nbsp;<code>Then</code> is called when a promise is resolved.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>See the following syntax to represent <code>then()</code>&nbsp;method:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code {"language":"jscript"} -->
<pre class="wp-block-syntaxhighlighter-code">promiseObject.then(onFulfilled, onRejected);</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>Note that, it takes two parameters:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>The&nbsp;<code>onFulfilled</code>&nbsp;callback is called if the promise is fulfilled. </li><li>The&nbsp;<code>onRejected</code>&nbsp;callback is called when the promise is rejected.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>The following function returns a&nbsp;<code>Promise</code>&nbsp;object:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code {"language":"jscript"} -->
<pre class="wp-block-syntaxhighlighter-code">function doPromise(finish) {
    return new Promise(function (resolve, reject) {
        setTimeout(() => {
            if (finish) {
                resolve("Your 🚗 has repaired.");
            } else {
                reject("Your 🚗 has not repaired yet.");
            }
        }, 4 * 1000);
    });
}</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>And the following calls the&nbsp;<code>doPromise()</code>&nbsp;function and invokes the&nbsp;<code>then()</code>&nbsp;method:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code {"language":"jscript"} -->
<pre class="wp-block-syntaxhighlighter-code">let res = doPromise(true);

res.then(
    success => console.log(success),
    reason => console.log(reason)
);</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:heading {"level":4} -->
<h4>2) The&nbsp;<code>catch()</code>&nbsp;method</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>  The&nbsp;<code>catch</code> is called when a promise is rejected.&nbsp; </p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code {"language":"jscript"} -->
<pre class="wp-block-syntaxhighlighter-code">res.catch(
    reason => console.log(reason)
);</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>Internally, the&nbsp;<code>catch()</code>&nbsp;method invokes the&nbsp;<code>then(undefined, onRejected)</code>&nbsp;method.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>3) The&nbsp;<code>finally()</code>&nbsp;method</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In every situtation want to execute the same piece of code whether the promise is resolved or rejected. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You can see the following example:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code {"language":"jscript"} -->
<pre class="wp-block-syntaxhighlighter-code">function carRepair() {
    // ...
}

res
    .then(
        (success) => {
            console.log(success);
            carRepair();
        }
    ).catch(
        (reason) => {
            console.log(reason);
            carRepair();
        }
    );
</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>As you can see, the&nbsp;<code>carRepair()</code>&nbsp;function call is duplicated in both&nbsp;<code>then()</code>&nbsp;and&nbsp;<code>catch()</code>&nbsp;methods.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To remove this duplicate and execute the&nbsp;<code>carRepair()</code>&nbsp;whether the promise is fulfilled or rejected, you use the&nbsp;<code>finally()</code>&nbsp;method, like this:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code {"language":"jscript"} -->
<pre class="wp-block-syntaxhighlighter-code">res
    .then(success => console.log(success))
    .catch(reason => console.log(reason))
    .finally(() => carRepair());</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:heading {"level":3} -->
<h3>JavaScript Promise Example</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In this example, we will show you how to load google news headlines from google webserver using json api.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Suppose that we have the following JSON file: <strong>https://newsapi.org/v2/top-headlines?country=us&amp;apiKey=e03753c9126b408d870a44318813ac3d</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>When you call this google news api, you will looks like:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code {"language":"jscript"} -->
<pre class="wp-block-syntaxhighlighter-code">{
   "status":"ok",
   "totalResults":38,
   "articles":[
      {
        {
         "source":{
            "id":"fox-news",
            "name":"Fox News"
         },
         "author":"Daniel Canova",
         "title":"Phil Mickelson teases big plans for 'The Match,' suggests Michael Jordan, Tony Romo, others could participate - Fox News",
         "description":"There’s no doubt about it that “The Match: Champions for Charity” lived up to the hype.",
         "url":"https://www.foxnews.com/sports/phil-mickelson-big-plans-the-match-michael-jordan-tony-romo",
         "urlToImage":"https://static.foxnews.com/foxnews.com/content/uploads/2020/05/The-Match-Champions-for-Charity-2.jpg",
         "publishedAt":"2020-05-27T22:48:22Z",
         "content":"There’s no doubt about it that “The Match: Champions for Charity” lived up to the hype.\r\nThe charity golf match featuring legends Tiger Woods, Phil Mickelson, Tom Brady and Peyton Manning raised $20 … [+2453 chars]"
      }
      }
   ]
}</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>The following shows the HTML page that contains a google news button. When you click the google news button, the page loads data from the google news webserver and display latest news headines:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code {"language":"xml"} -->
<pre class="wp-block-syntaxhighlighter-code">&lt;!DOCTYPE html>
&lt;html>
&lt;head>
    &lt;meta charset="utf-8">
    &lt;title>JavaScript Promise Demo&lt;/title>
&lt;/head>
&lt;body>
    &lt;div id="container">
        &lt;button id="btnGet">Get News&lt;/button>&lt;br>
        &lt;div id="news"> &lt;/div>
    &lt;/div>
    &lt;script src="">
    &lt;/script>
&lt;/body>
&lt;/html></pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>To load google news headlines from google news webserver, we’ll use the&nbsp;<code>XMLHttpRequest</code>&nbsp;object. Later, you will learn how to use the&nbsp;<code>fetch()</code>&nbsp;method.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The following function returns a Promise object that loads data from a remote file:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code {"language":"jscript"} -->
<pre class="wp-block-syntaxhighlighter-code">function load(url) {
    return new Promise(function (resolve, reject) {
        const request = new XMLHttpRequest();

        request.onreadystatechange = function (e) {
            if (this.readyState === 4) {
                if (this.status == 200) {
                    resolve(this.response);
                } else {
                    reject(this.status);
                }
            }
        }
        request.open('GET', url, true);
        request.responseType = 'json';
        request.send();
    });
}</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>Inside the new promise, call&nbsp;<code>resolve()</code>&nbsp;function and passed in the response if the HTTP status code is 200, otherwise, we invoked the&nbsp;<code>reject()</code>&nbsp;function and passed in the HTTP status code.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Register the button click event listener and call the&nbsp;<code>then()</code>&nbsp;method on the Promise. If the load is successful, then show google news headlines from the google news web server. Otherwise, we show the error message with the HTTP status code.</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code {"language":"jscript"} -->
<pre class="wp-block-syntaxhighlighter-code">const btn = document.querySelector('#btnGet');
const msg = document.querySelector('#news');
btn.onclick = function () {
    load('https://newsapi.org/v2/top-headlines?country=us&amp;apiKey=e03753c9126b408d870a44318813ac3d')
        .then(function(data) {
       
        for (i = 0; i &lt; data.articles.length; i++) {
              var node = document.createElement("LI");
              var textnode = document.createTextNode(data.articles[i].title);
              node.appendChild(textnode);
              document.getElementById("news").appendChild(node);
        }
       
    });
}</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>See the following output, when you call this api using js promise:</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":8677,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://www.tutsmake.com/wp-content/uploads/2020/05/output-google-new-api-1024x442.png" alt="" class="wp-image-8677"/></figure>
<!-- /wp:image -->

<!-- wp:heading -->
<h2>Conclusion</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In this tutorial you have learned the following:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>A promise is an object that returns a value in the future.</li><li>How to create a promise in javascript.</li><li>How to call promise with differents states.</li><li>A promise begins in the pending state and finishes in either fulfilled state or rejected state.</li><li>The&nbsp;<code>then</code> is called when a promise is resolved.&nbsp;  </li><li>The&nbsp;<code>catch</code> is called when a promise is rejected.&nbsp;  </li><li><code>finally()</code>&nbsp;method execute piece of code, whether the promise is resolved or rejected.</li><li>Call google news api and display news headlines using the js promises</li></ul>
<!-- /wp:list -->