<?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: Adam Blazek</title>
    <description>The latest articles on DEV Community by Adam Blazek (@princam).</description>
    <link>https://dev.to/princam</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%2F1061550%2F63350408-78d6-4374-9bf1-7895d128c148.jpeg</url>
      <title>DEV Community: Adam Blazek</title>
      <link>https://dev.to/princam</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/princam"/>
    <language>en</language>
    <item>
      <title>Promises in JavaScript: Understanding, Handling, and Mastering Async Code</title>
      <dc:creator>Adam Blazek</dc:creator>
      <pubDate>Mon, 02 Sep 2024 21:03:42 +0000</pubDate>
      <link>https://dev.to/princam/promises-in-javascript-understanding-handling-and-mastering-async-code-10kn</link>
      <guid>https://dev.to/princam/promises-in-javascript-understanding-handling-and-mastering-async-code-10kn</guid>
      <description>&lt;h2&gt;
  
  
  Intro
&lt;/h2&gt;

&lt;p&gt;I used to work as Java developer and I remember for the first time when I got in touch with promises in JavaScript. Even though the concept seemed simple, I still couldn’t fully grasp how Promises worked. It changed when I started to use them in projects and understood the cases they solved. Then came the AHA moment and all became more clear. Over time, Promises became a valuable weapon on my toolbelt. It is oddly satisfying when I can use them at work and solve the async handling between functions.&lt;/p&gt;

&lt;p&gt;You probably first come across Promises when fetching data from an API, which is also the most common example. Recently, I’ve been interviewed, and guess what was the first question “Can you tell me the difference between Promise and Async Await?”. I welcome that because I see it as a good starting point to know better how the applicant understands how the mechanisms work. However, he or she is mostly using other libraries and frameworks. It let me write down the differences and describe good practices for handling async function errors.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is the Promise
&lt;/h2&gt;

&lt;p&gt;Let’s start with the initial question: “What is the Promise?” &lt;strong&gt;Promise is a placeholder for the value that we don’t know yet&lt;/strong&gt; but we will get it as a result of asynchronous computation/function. If the promise goes well, then we will get the result. If the promise does not go well, then the promise will return an error.&lt;/p&gt;

&lt;h2&gt;
  
  
  A basic example of a Promise
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Defining a Promise
&lt;/h3&gt;

&lt;p&gt;You define Promise by calling its constructor and passing two callback functions: &lt;strong&gt;resolve&lt;/strong&gt; and &lt;strong&gt;reject&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;newPromise&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;reject&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Hello&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="c1"&gt;// reject('Error');&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We call &lt;code&gt;resolve&lt;/code&gt; function when we want to succesfully resolve the Promise. &lt;code&gt;reject&lt;/code&gt; is for rejecting the promise in the case when an error occurs during evaluating our logic.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Retrieving the Promise Result&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;We use the built-in function &lt;code&gt;then&lt;/code&gt; to get the Promise's result. It has two passed callbacks, &lt;code&gt;result&lt;/code&gt; and &lt;code&gt;error&lt;/code&gt;. The result is called when the Promise is successfully resolved by the function &lt;code&gt;resolve&lt;/code&gt;. If the Promise isn’t resolved, the second function &lt;code&gt;error&lt;/code&gt; is called. This function is triggered either by &lt;code&gt;reject&lt;/code&gt; or by another error that’s thrown.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nx"&gt;newPromise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;result&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Hello&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;There shouldn't be an error&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In our example, we will get the result &lt;code&gt;Hello&lt;/code&gt; because we successfully resolved the Promise.&lt;/p&gt;

&lt;h2&gt;
  
  
  Error handling of promises
&lt;/h2&gt;

&lt;p&gt;When the Promise is rejected then is always invoked its second &lt;code&gt;error&lt;/code&gt; callback.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;newPromise1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;reject&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nf"&gt;reject&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;An error occurred in Promise1&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="nx"&gt;newPromise1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
  &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;result&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// It is not invoked&lt;/span&gt;
  &lt;span class="p"&gt;},&lt;/span&gt;
  &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// 'An error occurred in Promise1'&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A more recommended approach for its clarity is to use the built-in &lt;code&gt;catch&lt;/code&gt; method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;newPromise2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;reject&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nf"&gt;reject&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;An error occurred in Promise2&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="nx"&gt;newPromise2&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;result&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// It is not invoked&lt;/span&gt;
  &lt;span class="p"&gt;})&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;catch&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// 'An error occurred in Promise2'&lt;/span&gt;
  &lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;catch&lt;/code&gt; method is chained and has provided its own error callback. It gets invoked when the Promise is rejected.&lt;/p&gt;

&lt;p&gt;Both versions work well but the chaining is IMO more readable and it is handy when using other built-in methods that we cover further.&lt;/p&gt;

&lt;h2&gt;
  
  
  Chaining promises
&lt;/h2&gt;

&lt;p&gt;The result of a promise could likely be another promise. In that case, we can chain an arbitrary number of &lt;code&gt;then&lt;/code&gt; functions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nf"&gt;getJSON&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;categories.json&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;categories&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Fetched categories:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;categories&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;getJSON&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;categories&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nx"&gt;itemsUrl&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;})&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;items&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Fetched items:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;items&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;getJSON&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;items&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nx"&gt;detailsUrl&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;})&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;details&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Fetched details:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;details&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;})&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;catch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;An error has occurred:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;message&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In our example, it serves to narrow down the search results to get details data. Each &lt;code&gt;then&lt;/code&gt; function can also have its error callback. If we care only about catching any error in the chain of calls, then we can leverage &lt;code&gt;catch&lt;/code&gt; function. It will be evaluated if any of the Promises return an error.&lt;/p&gt;

&lt;h2&gt;
  
  
  Promise all
&lt;/h2&gt;

&lt;p&gt;Sometimes we want to wait for the results of more independent promises and then act on the results. We can use the built-in function &lt;code&gt;Promise.all&lt;/code&gt; if we don’t care about the order of how the Promises got resolved.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;all&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;
    &lt;span class="nf"&gt;getJSON&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;categories.json&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
    &lt;span class="nf"&gt;getJSON&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;technology_items.json&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
    &lt;span class="nf"&gt;getJSON&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;science_items.json&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;])&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;results&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;categories&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;results&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;techItems&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;results&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;scienceItems&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;results&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;

        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Fetched categories:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;categories&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Fetched technology items:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;techItems&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Fetched science items:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;scienceItems&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Fetch details of the first item in each category&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;all&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;
            &lt;span class="nf"&gt;getJSON&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;techItems&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nx"&gt;detailsUrl&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
            &lt;span class="nf"&gt;getJSON&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;scienceItems&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nx"&gt;detailsUrl&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;]);&lt;/span&gt;
    &lt;span class="p"&gt;})&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;detailsResults&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;laptopDetails&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;detailsResults&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;physicsDetails&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;detailsResults&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;

        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Fetched laptop details:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;laptopDetails&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Fetched physics details:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;physicsDetails&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;})&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;catch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;An error has occurred:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;message&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Promise.all&lt;/code&gt; takes an array of Promises and returns an array of results. If one of the Promises is rejected then &lt;code&gt;Promise.all&lt;/code&gt; is rejected as well.&lt;/p&gt;

&lt;h2&gt;
  
  
  Racing promises
&lt;/h2&gt;

&lt;p&gt;Another built-in functionality is &lt;code&gt;Promise.race&lt;/code&gt;. It’s used when you have multiple asynchronous functions - Promises - and you want to race them.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;race&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;
    &lt;span class="nf"&gt;getJSON&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;technology_items.json&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
    &lt;span class="nf"&gt;getJSON&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;science_items.json&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;])&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;First resolved data:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;result&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;})&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;catch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;An error has occurred:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;message&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Execution of the Promises can take different times and &lt;code&gt;Promise.race&lt;/code&gt; evaluates the first resolved or rejected Promise from the array. It is used when we don’t care about the order but we want the result of the fastest asynchronous call.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Async Await
&lt;/h2&gt;

&lt;p&gt;As you can see, writing Promises requires a lot of boilerplate code. Luckily, we have the native &lt;strong&gt;Async Await&lt;/strong&gt; feature, which makes using Promises even easier. We mark a function by the word &lt;code&gt;async&lt;/code&gt; and by that, we say that somewhere in the code we will be calling asynchronous function and we should not wait for it. Then the async function is called with the &lt;code&gt;await&lt;/code&gt; word. &lt;/p&gt;

&lt;h3&gt;
  
  
  Basic example of Async Await
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;fetchData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Fetch the categories&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;categories&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;getJSON&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;categories.json&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Fetched categories:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;categories&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Fetch items from the first category (Technology)&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;techItems&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;getJSON&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;categories&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nx"&gt;itemsUrl&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Fetched technology items:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;techItems&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// Fetch details of the first item in Technology (Laptops)&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;laptopDetails&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;getJSON&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;techItems&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nx"&gt;detailsUrl&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Fetched laptop details:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;laptopDetails&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;An error has occurred:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;message&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="nf"&gt;fetchData&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our &lt;code&gt;fetchData&lt;/code&gt; is marked as &lt;code&gt;async&lt;/code&gt; and it allows us to use &lt;code&gt;await&lt;/code&gt; to handle asynchronous calls inside the function. We call more Promises and they will evaluated one after the other. &lt;/p&gt;

&lt;p&gt;We use &lt;code&gt;try...catch&lt;/code&gt; block if we want handle the errors. Rejected error is then caught in the &lt;code&gt;catch&lt;/code&gt; block and we can act on it like logging the error. &lt;/p&gt;

&lt;h2&gt;
  
  
  What’s different
&lt;/h2&gt;

&lt;p&gt;They are both features of JavaScript handling with asynchronous code. The main difference is in the syntax when Promises use chaining with &lt;code&gt;then&lt;/code&gt; and &lt;code&gt;catch&lt;/code&gt;  but &lt;code&gt;async await&lt;/code&gt; syntax is more in synchronous way. It makes it easier to read. Error handling for &lt;code&gt;async await&lt;/code&gt; is more straightforward when it leverages &lt;code&gt;try...catch&lt;/code&gt; block. This is a question that you can easily get at the interview. During the answer, you can get deeper into the description of both and highlight those differences.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Promise features&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Of course, you can use all the features with &lt;code&gt;async await&lt;/code&gt;. For example &lt;code&gt;Promise.all&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;fetchAllData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Use await with Promise.all to fetch multiple JSON files in parallel&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;techItems&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;scienceItems&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;laptopDetails&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;all&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;
            &lt;span class="nf"&gt;getJSON&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;technology_items.json&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
            &lt;span class="nf"&gt;getJSON&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;science_items.json&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
            &lt;span class="nf"&gt;getJSON&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;laptops_details.json&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;]);&lt;/span&gt;

        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Fetched technology items:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;techItems&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Fetched science items:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;scienceItems&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Fetched laptop details:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;laptopDetails&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;An error occurred:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;message&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Practical use cases
&lt;/h2&gt;

&lt;p&gt;Promises are a fundamental feature in JavaScript for handling asynchronous code. Here are the main ways it is used:&lt;/p&gt;

&lt;h3&gt;
  
  
  Fetching Data from APIs
&lt;/h3&gt;

&lt;p&gt;As was already shown in the examples above, this is one of the most used use cases for Promises and you work with it daily.&lt;/p&gt;

&lt;h3&gt;
  
  
  Handling file operations
&lt;/h3&gt;

&lt;p&gt;Reading and writing files asynchronously can be done using promises, especially by Node.js module &lt;code&gt;fs.promises&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nx"&gt;fs&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;fs/promises&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;writeFileAsync&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;filePath&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;content&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;options&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{})&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;fs&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;writeFile&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;filePath&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;content&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;options&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;`File successfully written to &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;filePath&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;`&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;`Error writing file to &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;filePath&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;:`&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;message&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;filePath&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;output.txt&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;fileContent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Hello, this is some content to write to the file!&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;fileOptions&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;encoding&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;utf8&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;flag&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;w&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;};&lt;/span&gt; &lt;span class="c1"&gt;// Optional file write options&lt;/span&gt;

&lt;span class="nf"&gt;writeFileAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;filePath&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;fileContent&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;fileOptions&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Promise based libraries
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;Axios&lt;/code&gt; is library that you should be familiar with. &lt;code&gt;Axios&lt;/code&gt; handles HTTP requests in client and is vastly used.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Express&lt;/code&gt; is a web framework for Node.js. It makes it easy to build web apps and APIs, and when you use promises with &lt;code&gt;Express&lt;/code&gt;, your code stays clean and easy to manage.&lt;/p&gt;

&lt;h2&gt;
  
  
  Repository with examples
&lt;/h2&gt;

&lt;p&gt;All the examples can be found at: &lt;a href="https://github.com/PrincAm/promise-example" rel="noopener noreferrer"&gt;https://github.com/PrincAm/promise-example&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;Promises are a fundamental part of JavaScript, essential for handling asynchronous tasks in web development. Whether fetching data, working with files, or using popular libraries like Axios and Express, you’ll frequently use promises in your code.&lt;/p&gt;

&lt;p&gt;In this article, we explored what Promises are, how to define and retrieve their results, and how to handle errors effectively. We also covered key features like chaining, &lt;code&gt;Promise.all&lt;/code&gt;, and &lt;code&gt;Promise.race&lt;/code&gt;. Finally, we introduced &lt;code&gt;async await&lt;/code&gt; syntax, which offers a more straightforward way to work with promises.&lt;/p&gt;

&lt;p&gt;Understanding these concepts is crucial for any JavaScript developer, as they are tools you’ll rely on daily.&lt;/p&gt;

&lt;p&gt;If you haven’t tried it yet, I recommend writing a simple code snippet to fetch data from an API. You can start with a &lt;a href="https://apilist.fun/" rel="noopener noreferrer"&gt;fun API&lt;/a&gt; to experiment with. Plus, all the examples and code snippets are available in &lt;a href="https://github.com/PrincAm/promise-example" rel="noopener noreferrer"&gt;this repository&lt;/a&gt; for you to explore.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Demystifying JSON Web Token (JWT): A Practical Overview</title>
      <dc:creator>Adam Blazek</dc:creator>
      <pubDate>Thu, 23 Nov 2023 09:09:42 +0000</pubDate>
      <link>https://dev.to/princam/demystifying-json-web-token-jwt-a-practical-overview-1kp0</link>
      <guid>https://dev.to/princam/demystifying-json-web-token-jwt-a-practical-overview-1kp0</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;After reading this article, you will learn what JWT stands for, what are its parts, and what is its use in communication between client and server. You will find the mechanism of JWT simple and useful!&lt;/p&gt;

&lt;h2&gt;
  
  
  What is JWT
&lt;/h2&gt;

&lt;p&gt;JWT stands for Jason Web Token and the main purpose is to enable secure data transmission between the parts. They are usually the client and the server. JWT can be passed in the header of HTTP request, as a body parameter of POST request, or parameter in URL request but it is less common and secure. The practice is to pass the JWT in the &lt;code&gt;Authorization&lt;/code&gt; header. It is the most secure way because it is prevented from being logged which reduces the risk of exposure. Here is a simple example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nf"&gt;fetch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;https://example.com/endpoint&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;method&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;POST&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;headers&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Content-Type&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;application/json&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Authorization&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;`Bearer &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;YOUR_JWT_TOKEN&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;`&lt;/span&gt;
  &lt;span class="p"&gt;},&lt;/span&gt;
  &lt;span class="na"&gt;body&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;JSON&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;stringify&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can see that JWT is sent as Bearer token. Bearer token is type of token primarily used for authorization and it is usually associated with OAuth 2.0. &lt;/p&gt;

&lt;h2&gt;
  
  
  Purpose of JWT
&lt;/h2&gt;

&lt;p&gt;JWT token can hold information that is encrypted and is available right away. It means it will avoid extra calling the database. Usually JWT has information about the user but it is also used for &lt;strong&gt;authorization&lt;/strong&gt;. After login, calls of APIs must have access token which is the JWT. Then the user is allowed to make such a call.&lt;/p&gt;

&lt;p&gt;Now, let's cover parts of the token. JWT consists of header, payload, signature. &lt;/p&gt;

&lt;h3&gt;
  
  
  Header
&lt;/h3&gt;

&lt;p&gt;Header keeps information about what type of token it is and how the JWT is encoded. It can be for example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;alg&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;HS253&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;type&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;JWT&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is the first part of the JWT. Here is base64url encoded:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nx"&gt;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The client is not doing a lot with the header. It sends the JWT with the header to server and server then takes the alg information from header to verify signature.&lt;/p&gt;

&lt;h3&gt;
  
  
  Payload
&lt;/h3&gt;

&lt;p&gt;Payload part holds the data about the entity, usually the user, and other metadata. Data is so cold &lt;code&gt;claims&lt;/code&gt;. This is an example of a simple payload:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;sub&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;1234567890&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="c1"&gt;// subject, usually the ID&lt;/span&gt;
  &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;name&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Adam&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;admin&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="c1"&gt;// custom claim&lt;/span&gt;
  &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;iat&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1516239022&lt;/span&gt; &lt;span class="c1"&gt;// issued at, timestamp when the token was created&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Payload is not encrypted, sometime is it not even encoded therefore it should not contain any sensitive information.&lt;/p&gt;

&lt;h3&gt;
  
  
  Signature
&lt;/h3&gt;

&lt;p&gt;Signiture is the last part of the token. It is used to verify that the sender of the token is who says it is and that token wasn’t changed along the way. Steps to create a signature are: Firstly, you have take the encoded header, the encoded payload, a secret, algorithm specified in the header and sign it. Pseudocode to create a signature can look like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="c1"&gt;// pseudo code&lt;/span&gt;
&lt;span class="nc"&gt;HMACSHA256&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
  &lt;span class="nf"&gt;base64UrlEncode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;header&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;.&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt;
  &lt;span class="nf"&gt;base64UrlEncode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;payload&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
  &lt;span class="nx"&gt;secret&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The purpose of the signature is to secure the token agains uncotrolled changes and to verify the sender of the JWT is who it says it is.&lt;/p&gt;

&lt;h2&gt;
  
  
  Practical example
&lt;/h2&gt;

&lt;p&gt;And now we can go step by step through to real scenario how is JWT treated during the HTTP call and authorization.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;User Login&lt;/strong&gt;&lt;br&gt;
First step is the user login. He fills the credentials on the login page and sends them to the server.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Verification&lt;/strong&gt;&lt;br&gt;
The server validates the credentials against the database and if the login is successful then the JWT is created.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;JWT Creation&lt;/strong&gt;&lt;br&gt;
As we described in the previous chapter, JWT contains payload with user information and claims. The server uses secret to sign the JWT that ensures that the JWT hasn’t been transformed on the way from the client.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Token Transmission&lt;/strong&gt;&lt;br&gt;
Then the server sends the token to client usually as response to the HTTP request.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Client Stores the Token&lt;/strong&gt;&lt;br&gt;
Client might to store the JWT in the browser’s local storage, cookie or session storage.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Subsequent Requests&lt;/strong&gt;&lt;br&gt;
Then with every subsequent  request to the server, JWT is usually included in the header of HTTP request as &lt;code&gt;Authorization: Bearer &amp;lt;token&amp;gt;&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Server JWT Validation&lt;/strong&gt;&lt;br&gt;
When the server receives HTTP request with the token, then it validates the signature to ensure it is legitimite. If the token is valid and not expired then the server returns requested response.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Token Expiration and Refresh&lt;/strong&gt;&lt;br&gt;
JWT often contains information about expiration time (exp claim). Token can’t be used when is expired. Application may use refresh token mechanism to issue a new JWT without need to login again.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In summary, we've covered the building blocks of JSON Web Tokens (JWT): the header, payload, and signature. We've also highlighted how JWT serves as a handy tool for passing information between the client and server. Importantly, when included in a request's header, JWT acts as a way to authorize and secure the communication between the two. It's like a secret passcode that ensures smooth and safe data exchange in web applications.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
    </item>
    <item>
      <title>JavaScript Event Loop simply explained</title>
      <dc:creator>Adam Blazek</dc:creator>
      <pubDate>Wed, 06 Sep 2023 08:08:45 +0000</pubDate>
      <link>https://dev.to/princam/javascript-event-loop-simply-explained-5d75</link>
      <guid>https://dev.to/princam/javascript-event-loop-simply-explained-5d75</guid>
      <description>&lt;p&gt;In order to better understand how the browser works, it is good to know the event loop and the event queue. It will also complete the picture of single-threaded JavaScript and answers your questions like &lt;em&gt;"How is possible that the task is completed asynchronously?"&lt;/em&gt;. Knowing how the event loop works can help you understand why JavaScript and web browsers might have some speed or performance issues. You can think about the event loop as the main function of the browser which infinitely takes task after task until interaction with the browser ends.&lt;/p&gt;

&lt;h2&gt;
  
  
  Event Loop
&lt;/h2&gt;

&lt;p&gt;The event loop has at least two queues that hold actions. In practice, it has even more but we will stay with two. Actions are called &lt;em&gt;tasks&lt;/em&gt; and can be divided into Microtasks and Macrotasks. Tasks in the queue are executed in order first in, first out.&lt;/p&gt;

&lt;h2&gt;
  
  
  Macrotasks
&lt;/h2&gt;

&lt;p&gt;Macrotasks are often called just &lt;em&gt;tasks&lt;/em&gt;. Their purpose includes &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;creating the main document object&lt;/li&gt;
&lt;li&gt;parsing HTML&lt;/li&gt;
&lt;li&gt;executing mainline JavaScript code&lt;/li&gt;
&lt;li&gt;changing URL&lt;/li&gt;
&lt;li&gt;page loading&lt;/li&gt;
&lt;li&gt;timer events&lt;/li&gt;
&lt;li&gt;network events&lt;/li&gt;
&lt;li&gt;and more...&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When the macrotask is finished, then the browser can continue with other assignments like UI re-rendering or garbage collection.&lt;/p&gt;

&lt;h2&gt;
  
  
  Microtasks
&lt;/h2&gt;

&lt;p&gt;Microtasks are smaller types of tasks that usually update the state of the application and should be done before UI re-rendering. Example includes&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;promise callback&lt;/li&gt;
&lt;li&gt;DOM mutation changes&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Microtasks are actions that should be done before the re-rendering, executed before Macrtotasks, and therefore avoid unnecessary UI re-renders. It could then lead to an inconsistent state of the application and we definitely don't want it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Lifecycle
&lt;/h2&gt;

&lt;p&gt;We should know two main principles:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Tasks are handled one at a time&lt;/li&gt;
&lt;li&gt;A task has to be completed and can't be interrupted by another task&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's take a look at the following diagram and go through one iteration of the event loop to better understand how these principles are applied.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4zvx3t5td2cokxydtgn4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4zvx3t5td2cokxydtgn4.png" alt="Event loop"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;At the start, the event loop first checks if there is a macrotask in the macrotask queue waiting for execution. If there is, it executes just that one macrotask. Once that one macrotask is fully completed or the queue is empty, then the event loop moves to process the microtask queue. It checks to see if there are any microtasks waiting for execution. It executes all microtasks one by one to full completion. Notice the difference between the macrotask and microtask queues. Only one task from the macrotask queue is processed but all the tasks from microtask queue have to be completed before the event loop moves to the rendering of UI. After the microtask queue is empty, the event loop continues to the rendering phase. It checks if UI needs to be rerendered. If the rerendering is resolved, then the event loop is finished and goes back to the start and checks if the macrotask queue is not empty.&lt;/p&gt;

&lt;h2&gt;
  
  
  Downside
&lt;/h2&gt;

&lt;p&gt;Downside of this model is that if the task takes too long, user is not able to interact with UI, like click or scroll. Browser tends to render 60 frames per second, it is one rerendering each 16ms. So if the task takes more than 16ms then you can see that browser froze until the task didn't run to completion.&lt;/p&gt;

&lt;p&gt;It is good practice to divide such a task into smaller pieces and execute them using &lt;code&gt;setTimeout&lt;/code&gt; or &lt;code&gt;webworkers&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Other resources
&lt;/h2&gt;

&lt;p&gt;The video &lt;em&gt;What the heck is the event loop anyway?&lt;/em&gt; by Philip Roberts is legendary and one of the best explanations of how the event loop works. The model they show is simpler than our example, but I'd still suggest watching it. It's a good starter guide and it's entertaining!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ" rel="noopener noreferrer"&gt;https://www.youtube.com/watch?v=8aGhZQkoFbQ&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;The event loop typically has one or more queues. Usually, there's at least one for macrotasks and another one for microtasks. In one go-around of the loop, only one macrotask is run to completion but all the microtasks are completed before the next rerendering. The browser runs rerendering every 16ms for a smooth UI experience, so task execution shouldn't take more time.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>JavaScript Closures simply explained</title>
      <dc:creator>Adam Blazek</dc:creator>
      <pubDate>Mon, 10 Jul 2023 20:08:58 +0000</pubDate>
      <link>https://dev.to/princam/javascript-closures-simply-explained-16nf</link>
      <guid>https://dev.to/princam/javascript-closures-simply-explained-16nf</guid>
      <description>&lt;p&gt;Closures are one of the main pillars of JavaScript. It is also a popular interview question. So, it's really useful to understand what closures are and what we can do with them.&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding Closures
&lt;/h2&gt;

&lt;p&gt;Simply said, closures allow accessing variables outside the function. Closure is a combination of a function bundled together with references to its surrounding state. It means that the function can access and manipulate variables located in the outer function's scope even after the outer function has finished. Then if the function is called at a time when the external scope with the variable already doesn't exist, the function still keeps access to the variable. It creates a bubble around our function, it keeps all variables in a scope when the function was created. Let's take a look at the following code snippet. It is a classic example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const outerFunction = (outerVariable) =&amp;gt; {
  const innerFunction = (innerVariable) =&amp;gt; {
    console.log('outerVariable:', outerVariable);
    console.log('innerVariable:', innerVariable);
  }
  return innerFunction;
}

const newFunction = outerFunction('outside');
newFunction('inside');
// logs outerVariable: outside
// logs innerVariable: inside

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;innerFunction&lt;/code&gt; is a closure that is created when we call &lt;code&gt;outerFunction&lt;/code&gt; and it keeps access to the &lt;code&gt;outerFunction&lt;/code&gt; scope after the &lt;code&gt;outerFunction&lt;/code&gt; was executed.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc9lekxoof4euar1wa2s3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc9lekxoof4euar1wa2s3.png" alt="Closure is like a bubble"&gt;&lt;/a&gt;&lt;br&gt;
Closure is like a protective bubble. Closure for the &lt;code&gt;innerFunction&lt;/code&gt; keeps the variables in the function's scope alive as long as the function exists.&lt;/p&gt;
&lt;h2&gt;
  
  
  Practical examples
&lt;/h2&gt;

&lt;p&gt;Closures are used a lot in JavaScript, even when we don't always notice it. For example in data privacy, factory functions, stateful functions, and can often be found in JavaScript libraries and frameworks.&lt;br&gt;
Now, we will go through two practical examples where we will explain how the Closures work.&lt;/p&gt;
&lt;h3&gt;
  
  
  Private variables
&lt;/h3&gt;

&lt;p&gt;JavaScript doesn't support private variables but we can achieve a similar behavior by using a Closure. When we don't want to allow direct access to a variable, we can create accessors - the getters and setters - to enable them outside of the function. Let's describe it better in the following example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const post = () =&amp;gt; {
  let likes = 0; // private variable

  return {
    getLikes: () =&amp;gt; {
      return likes;
    },
    like: () =&amp;gt; {
      return likes++;
    };
  }
}

var post1 = post();
post1.like();

console.log(post1.likes); // undefined
console.log(post1.getLikes()); // 1

var post2 = post();

console.log(post2.getLikes()); // 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First, we declare the private variable &lt;code&gt;likes&lt;/code&gt; inside the function's constructor. &lt;code&gt;likes&lt;/code&gt; is in the function's scope and isn't accessible from outside. Then we create the accessor method for likes count. Defining the getter we give read-only access to the value. The second method is for incremental increasing the number of likes. No one can change the value more than we allow. In the end, if you check the console, you'll see that we can't get &lt;code&gt;likes&lt;/code&gt; directly. But, we can find out the value by using &lt;code&gt;getLikes()&lt;/code&gt;, or add more likes by calling &lt;code&gt;like()&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Callback as a Closure
&lt;/h3&gt;

&lt;p&gt;It is another practical example of when we do asynchronous fetching of data and then updating the UI or logging. Check out this example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fetchData = (url, callback) =&amp;gt; {
  // It is simulating an asynchronous operation
  setTimeout(() =&amp;gt; {
    const data = { name: 'Adam', age: 20 };
    callback(data);
  }, 2000);
}

const processUserData = (user) =&amp;gt; {
  console.log('Name:', user.name);
  console.log('Age:', user.age);
}

fetchData('https://example.com/api/user', processUserData);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;fetchData&lt;/code&gt; function takes two parameters. The first one is an url from which we fetch data. The second one is the callback that will be called after the asynchronous call is done. &lt;code&gt;processUserData&lt;/code&gt; function is our callback function and also it is the Closure! When the &lt;code&gt;fetchData&lt;/code&gt; is executed then &lt;code&gt;setTimeout&lt;/code&gt; is called and the callback has access to the outer user data. And the access remains even after the execution of the &lt;code&gt;fetchData&lt;/code&gt; is finished. &lt;br&gt;
This is a common way how callback can access data returned by async fetch and then do various things, for example, update the UI.&lt;/p&gt;

&lt;h2&gt;
  
  
  Disadvantage
&lt;/h2&gt;

&lt;p&gt;As you can see, the biggest downside is that Closure comes with an extra bag of other variables. This can use up more memory than needed if we're not careful.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;We talked about a Closure as a function having access to variables that were in the outer scope at the time when the closure was defined. Closures have many practical applications. We describe how are used as accessors to private variables - the getters and setters - or together with a callback function for updating the user interface based on asynchronously fetched data.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>JavaScript Object Prototypes simply explained</title>
      <dc:creator>Adam Blazek</dc:creator>
      <pubDate>Wed, 24 May 2023 19:31:45 +0000</pubDate>
      <link>https://dev.to/princam/javascript-object-prototypes-simply-explained-4cno</link>
      <guid>https://dev.to/princam/javascript-object-prototypes-simply-explained-4cno</guid>
      <description>&lt;p&gt;Did you hear about object prototypes but you weren't sure what they exactly do? They are mentioned here and there but you never got in touch with them? The concept of object prototypes is not difficult and when you will have a better understanding of their purpose, suddenly other principles will get more clear to you as well. For example, how JavaScript Classes work.&lt;/p&gt;

&lt;p&gt;Let's start with an explanation of JavaScript objects. What they are and how they behave.&lt;/p&gt;

&lt;h2&gt;
  
  
  JavaScript Objects
&lt;/h2&gt;

&lt;p&gt;Object is one of JavaScript's &lt;em&gt;data types&lt;/em&gt;. Object can have properties holding values as key-value pair. Property value can be a value of any type. It can be for example string, number, or function. When the value is a function, then it is called the object's &lt;em&gt;method&lt;/em&gt;. &lt;br&gt;
Object is created by using curly braces &lt;code&gt;{}&lt;/code&gt; but can be also created by a call of &lt;code&gt;Object()&lt;/code&gt; constructor. The second option is not used much in daily work.&lt;br&gt;
This is example of the initialization of a new simple object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const vegetable = {
  taste: 'good',
  isHealthy: true,
  calories: 65
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We create a new object called &lt;code&gt;vegetable&lt;/code&gt; with three properties describing the vegetable. And that is. The object is another type of how to describe data.&lt;br&gt;
Object property can also point to another object. We can illustrate it in the example of the vegetable &lt;code&gt;zucchini&lt;/code&gt; which was originally bred in Milan, Italy.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const milan = {
  name: 'Milan',
  country: 'Italy'
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const zucchini = {
  color: 'green',
  taste: 'delicious',
  placeOfOrigin: milan
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, we simply use dot notation to get the name of the zucchini's place of origin, &lt;code&gt;zucchini.placeOfOrigin.name&lt;/code&gt; is &lt;code&gt;Milan&lt;/code&gt;. &lt;/p&gt;

&lt;h2&gt;
  
  
  Object Prototypes
&lt;/h2&gt;

&lt;p&gt;Let's move further and investigate if that's all that the object includes!&lt;br&gt;
If you log an empty object into a console, you can see that the object isn't actually empty! There are a lot of extra methods. Those methods &lt;code&gt;toString()&lt;/code&gt;, &lt;code&gt;toLocaleString()&lt;/code&gt;, &lt;code&gt;valueOf()&lt;/code&gt;, and more are defined in the object &lt;em&gt;prototype&lt;/em&gt;!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgqfoav3na68sxqhlft9a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgqfoav3na68sxqhlft9a.png" alt="Log on JavaScript empty object"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Object prototype is a built-in property that every object has. Prototype itself is an object that has another prototype and optional properties. It adds an additional description to the original object. Now, we will explain it with an example.&lt;/p&gt;

&lt;p&gt;We have the &lt;code&gt;vegetable&lt;/code&gt; object with a few properties.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const vegetable = {
  taste: 'good',
  isHealthy: true,
  calories: 65
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, we define the &lt;code&gt;vegetable&lt;/code&gt; as the prototype of the &lt;code&gt;zucchini&lt;/code&gt; using the &lt;code&gt;__proto__&lt;/code&gt; property.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const zucchini = {
  color: 'green',
  taste: 'delicious',
  placeOfOrigin: milan,
  __proto__: vegetable
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Prototype chain
&lt;/h3&gt;

&lt;p&gt;When we want to know what color zucchini has, it takes a look if the object &lt;code&gt;zucchini&lt;/code&gt; has a property called &lt;code&gt;color&lt;/code&gt;, it has and returns its value &lt;code&gt;green&lt;/code&gt;.&lt;br&gt;
&lt;code&gt;zucchini.color&lt;/code&gt; is &lt;code&gt;'green'&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Then, if we want to know how many calories zucchini has, it checks &lt;code&gt;zucchini&lt;/code&gt; object, there is no &lt;code&gt;calories&lt;/code&gt; property. It continues to take a look into &lt;code&gt;prototype&lt;/code&gt; object. And &lt;code&gt;__proto__&lt;/code&gt; refers to &lt;code&gt;vegetable&lt;/code&gt; that contains &lt;code&gt;calories&lt;/code&gt;. It then returns the value &lt;code&gt;65&lt;/code&gt;. &lt;br&gt;
&lt;code&gt;zucchini.calories&lt;/code&gt; is &lt;code&gt;65&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Also, if we want to know the taste of the zucchini, it goes to &lt;code&gt;zucchini&lt;/code&gt; object, finds the property &lt;code&gt;taste&lt;/code&gt;, and returns the value &lt;code&gt;delicious&lt;/code&gt;. It doesn't continue with searching for the taste in prototype although there is also a defined &lt;code&gt;taste&lt;/code&gt; property. This is called &lt;em&gt;shadowing&lt;/em&gt; the property.&lt;br&gt;
&lt;code&gt;zucchini.taste&lt;/code&gt; is &lt;code&gt;'delicious'&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Lastly, if we want to know the value of the property &lt;code&gt;isVegan&lt;/code&gt;, then it checks &lt;code&gt;zucchini&lt;/code&gt; object. There is no property called &lt;code&gt;isVegan&lt;/code&gt;. It continues to the prototype object. It is the object &lt;code&gt;vegetable&lt;/code&gt; but there also isn't any property &lt;code&gt;isVegan&lt;/code&gt;. Therefore, the value is &lt;code&gt;undefined&lt;/code&gt;.&lt;br&gt;
&lt;code&gt;zucchini.isVegan&lt;/code&gt; is &lt;code&gt;undefined&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;And that's it! Prototype is used for many powerful features in JavaScript. We can combine objects and reuse the code. Prototype is leveraged for &lt;em&gt;inheritance&lt;/em&gt; in JavaScript and is hidden under the roof of JavaScript &lt;em&gt;Classes&lt;/em&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Recapitulation
&lt;/h2&gt;

&lt;p&gt;We learned what are the objects in JavaScript and that they can have properties with values. Property value can point to another object. Further, we found out that an empty object is not quite empty but has built-in methods in the &lt;code&gt;prototype&lt;/code&gt; object. We can add properties to the prototype, it is called prototype chaining and it extends the original object. This principle is used for &lt;em&gt;inheritance&lt;/em&gt; in JavaScript.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
