<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vishal Reddy Chintham on Medium]]></title>
        <description><![CDATA[Stories by Vishal Reddy Chintham on Medium]]></description>
        <link>https://medium.com/@chinthamvishal1408?source=rss-1994e2462401------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DCDu9kNgUI8XATnpPwY9JA.jpeg</url>
            <title>Stories by Vishal Reddy Chintham on Medium</title>
            <link>https://medium.com/@chinthamvishal1408?source=rss-1994e2462401------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:20:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chinthamvishal1408/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Puzzled about Asynchronous Code in JavaScript ?]]></title>
            <link>https://medium.com/@chinthamvishal1408/puzzled-about-asynchronous-code-in-javascript-f9fc59d05dc2?source=rss-1994e2462401------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9fc59d05dc2</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[callback]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[Vishal Reddy Chintham]]></dc:creator>
            <pubDate>Mon, 16 Nov 2020 14:05:36 GMT</pubDate>
            <atom:updated>2020-11-16T17:36:56.247Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qi6xLYFjKWWJdMZI" /><figcaption>Photo by <a href="https://unsplash.com/@evan__bray?utm_source=medium&amp;utm_medium=referral">Evan Dennis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Ambiguous about Asynchronous Code in JavaScript ?</h3><p>Hey JavaScript enthusiasts, I am Vishal and I am very much excited to have you on board today 😁. This article will give you a clear understanding of asynchronous code and help you tackle the issues related to asynchronous code. I am gonna start it with the most important note:</p><blockquote>JavaScript is synchronous and a single threaded language but it can have pieces of code whose execution can be delayed (Asynchronous code).</blockquote><p>Don’t worry if you are not able wrap your head around this statement, we’ll be on the same page by the end of the article 😃.</p><h3>Synchronous code</h3><p>The Code that gives the desired result without any delay is called the <strong>Synchronous code</strong>. A simple implementation of it :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*9JEGX4potvs48gIw9VL-Ug.png" /><figcaption>A simple implementation of a function call for incrementing a number</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*FVxFlCa9TaysJ59w7tPy3Q.png" /><figcaption>Output for the above code</figcaption></figure><p>Yeah, you got it right. I totally understand that you don’t have any problem with the above code. Then let’s dive into the asynchronous code.</p><h3>Asynchronous Code👻</h3><p><strong>Asynchronous code </strong>gives the result, but with a delay( i.e. result is given at a later point of time as the code execution is not completed instantly). You need to be aware of the fact that, the code that depends on the output of the asynchronous code gives unexpected results, if the asynchronous code is not handled properly. You can find the consequence of not handling asynchronous code properly, in the below example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*fXo8eVqD0NscAF0nml8O9Q.png" /><figcaption>asynchronous code example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*9CByUR-3QX_AC6A9-z_7aA.png" /><figcaption>Output for the above code</figcaption></figure><p>We can see that, <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout">setTimeout</a> function delays the statements by 2 seconds(2000 milliseconds).Our interpreter is always in a hurry to complete the execution and it won’t wait for 2 seconds. Therefore, it completes the function execution without executing any return statement(i.e. nothing is returned back). Hence, the value of ‘a’ is undefined.</p><h3><strong>SOLUTION 😇</strong></h3><p>Asynchronous code is seen very often in JavaScript. We understood that it is highly important to handle the asynchronous code as it might even break our entire program. These are the three methods to handle it:</p><ol><li>Using Callbacks</li><li>Using Promises</li><li>Using Async, await</li></ol><h3>1.Using Callbacks</h3><blockquote>A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. — MDN DOCS</blockquote><p>We can use Callbacks for handling asynchronous code, using the following steps:</p><ul><li>Add a parameter for the function(that executes asynchronously).This allows us to pass a callback function in the function call.</li><li>Once the result is generated inside the function, callback function must be called by passing the result as an argument.</li><li>A callback function must be passed as one of the arguments in the function call.</li><li>Put the code that depends on the result(produced by the asynchronously executing function) inside the callback function.</li></ul><p>A practical implementation of the listed steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*J3ByhEWb1o-FQ-gnKcqPfQ.png" /><figcaption>Handling asynchronous code using a callback function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*n5sPjxFC6X-bANWGh3-KkA.png" /><figcaption>Output for the above code</figcaption></figure><p>BINGO! A method to solve your issues with asynchronous code. Hold on till the end, you will get an easier and a simpler method to handle the asynchronous code.</p><h3><strong>2. Using Promises</strong></h3><blockquote>A <strong>Promise</strong> is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action&#39;s eventual success value or failure reason</blockquote><blockquote>— MDN Docs</blockquote><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise"><strong>Promise</strong></a> is an object that promises us an output from the asynchronous code. We can handle the output(result or error) returned by the asynchronous code efficiently by the predefined handlers provided by a promise.</p><p>We can handle asynchronous code with promises using the following steps :</p><ol><li><strong>Creating a promise</strong></li></ol><p>A promise is generally created in the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*H0EO6_OVMZdltPpT5P__0A.png" /></figure><ul><li>The whole asynchronous code is passed inside the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions">anonymous function</a>.</li><li><strong>resolve callback</strong> is called when a result must be sent from asynchronous code.</li><li><strong>reject callback</strong> is called when an error must be sent from the asynchronous code. We can pass anything to reject callback as it will anyways convert it to an error object.</li><li>When any one of the callback is called, the promise state is changed from <strong>pending </strong>to <strong>settled</strong>.</li></ul><p><strong>2. Handling the promise</strong></p><p>The promise can be handled using the predefined handlers as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*pKQjAQN7P89ZEooyYo7lnQ.png" /></figure><ul><li>If the resolve callback is called, we can access the result by .then() handler.</li><li>If the reject callback is called, we can handle the error by .catch() handler.</li><li>The code inside .finally() is always executed irrespective of what is received from the asynchronous code.</li></ul><p>Phew! that’s a lot of theory. Practical example will make it simpler, right ? There you go :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*uAVMGATrfAyHDRDEjGYJJQ.png" /><figcaption>Handling asynchronous code using a promise and the provided handlers</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*XYSGBLdTQMgCR3WW-kwvaQ.png" /><figcaption>Output for the above code</figcaption></figure><p>Yeah, promises offer an easy and efficient way to handle the asynchronous code than callbacks.</p><blockquote>Generally, promises are preferred over callbacks to avoid the <a href="http://callbackhell.com/"><strong>Callback Hell</strong></a><strong>.</strong></blockquote><h3><strong>3. Using Async/Await</strong></h3><blockquote>Async/Await keywords are the most recent additions to the JavaScript. These features basically act as syntactic sugar on top of promises, making asynchronous code easier to write and to read afterwards.</blockquote><blockquote>— MDN Docs</blockquote><h3><strong>Async</strong></h3><p>Async keyword is used right before a function keyword. It makes the function asynchronous and the function can be called as <strong>Async Function</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*P2BkFfht5dEwIn5Y3Nf3fg.png" /><figcaption>syntax for defining async functions</figcaption></figure><ul><li><strong>Async functions</strong> are the only place where we can use <strong>await</strong> keyword.</li><li>Only promises are returned by the async functions. (whatever the function returns, they are converted to promises by default).</li></ul><h3><strong>Await(valid in async functions only)</strong></h3><p>Await keyword is placed exactly in front of a promise object or an async function. When await keyword is used, the interpreter goes to the next line, only when the promise is settled. We will come across two cases when we deal with the promises, using await keyword.</p><ol><li><strong>Result returned</strong></li></ol><p>When result is returned, it can be stored in a variable as shown below. (Storing it to a variable is completely optional).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*9VjjqMeSmH3VL03tKJZhRw.png" /><figcaption>A demo async function has been called that uses await keyword to resolve the promise</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*0YXSCtnOMDyL1AGrMZ_w3g.png" /><figcaption>Output for the above code</figcaption></figure><p><strong>2. Error returned</strong></p><p>The statement with await keyword throws an error when the promise is settled by calling the reject callback function (as an error is returned).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*npkF4kIn-76y_89ogkT1Bw.png" /><figcaption>Promise is rejected in this case</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*Pi5TqSsfHlohajb-jMB0Nw.png" /><figcaption>Output for the above code</figcaption></figure><p><strong>Therefore, it is very clear that we can’t use the above implementation of async/await as it doesn’t take care of all the cases.</strong></p><h3><strong>Using Async/Await with Try/Catch</strong></h3><p>The following method is the efficient and standard usage of async/await :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*ViSBhFdGsIsc2fkm_Vwabg.png" /><figcaption>Standard implementation of async/await keywords</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*nzGHCGKu7yBVbCjlSSD25A.png" /><figcaption>Output for the above code</figcaption></figure><blockquote>Using Async/await is preferred over the second method as, it is more simpler to implement and we can also avoid the endless chaining of the handlers.</blockquote><blockquote>In this article, We’ve looked at the implementation of the methods for handling the asynchronous code. You are encouraged to learn the in-depth theory present behind the scenes in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">MDN Docs</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9fc59d05dc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>