<?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 Dilip Thakur on Medium]]></title>
        <description><![CDATA[Stories by Dilip Thakur on Medium]]></description>
        <link>https://medium.com/@dilipthakur87?source=rss-2251464f02b2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fJ9DjoRoHS5c_rqzv4TUqA.jpeg</url>
            <title>Stories by Dilip Thakur on Medium</title>
            <link>https://medium.com/@dilipthakur87?source=rss-2251464f02b2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:08:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dilipthakur87/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[Understanding the Concept of Redux]]></title>
            <link>https://blog.devgenius.io/understanding-the-concept-of-redux-5a50acfe38d?source=rss-2251464f02b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a50acfe38d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[redux-thunk]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[redux-for-beginner]]></category>
            <dc:creator><![CDATA[Dilip Thakur]]></dc:creator>
            <pubDate>Mon, 09 May 2022 08:38:14 GMT</pubDate>
            <atom:updated>2022-05-25T20:56:20.850Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Redux is a pattern and library for managing and updating application state, using events called “actions”. In other words, the Redux pattern provides state management for JavaScript apps.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4fXkuzba0qZpKaqTPw6yA.png" /></figure><p><em>What does that actually mean? What is managing states? What are states?</em></p><p>It was still confusing to me when I read that statement first when I was trying to learn Redux. I knew the definition but I was still confused about what it actually was.</p><p>So, to get a better idea of what Redux actually is, we need to know about states and state management first. It will help us understand the concept of redux in a better way.</p><h3>So, what is “state”?</h3><p>“State” is a plain JavaScript object used by React to represent information about the component’s current situation.</p><p>It’s managed in the component (just like any variable declared in a function). The major difference between class variables and states is that the component is re-rendered when a state is updated and thus the updated value is displayed but it doesn’t happen with class variables as <strong><em>render()</em></strong> is not called when a class variable is updated.</p><blockquote><strong>Note: React class components have a <em>forceUpdate </em>method that triggers the render method. By calling <em>this.forceUpdate()</em> after updating our class variable, we can manually call <em>render()</em> i.e., get our displayed value to update.</strong></blockquote><p>Below is a sample example of how you can define, use and change states in React. While changing a state, we can simply call <strong><em>this.setState()</em></strong> and pass it an object or a function that returns an object instead of manually assigning the variable. Calling <strong><em>this.setState()</em></strong> merges the passed object into the current state to create a new state object and if that results in a changed value, <strong><em>render()</em></strong> is called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xANlzzM_Emj-bwUSvLv7fw.png" /></figure><p><em>Now that we have a better idea of what a state is, let’s take a look at state management.</em></p><h3>What’s state management?</h3><p>State Management is nothing but managing data across the components. It’s the implementation of a Design Pattern, with the help of this design pattern we can synchronize the state of the application throughout all components of the application.</p><blockquote>This means creating a structure for the way in which you access and modify your application state. You could think of this as managing “frontend databases”.</blockquote><p><strong><em>Now that we are somewhat familiar with both “States” and “State Management”, let’s get back to our main concern and go through the definition of Redux that we came across at the beginning of this article.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ppybpyqqYun_xomJT_7Svw.png" /></figure><p><strong><em>Well, the definition seems to be more familiar now. Redux simply allows us to maintain a predictable state container for our javascript apps.</em></strong></p><blockquote>Managing the states of an app can be a total mess if the app grows bigger. To overcome these situations, there are multiple state management tools available, and <strong><em>“Redux”</em></strong> is one of the most popular state management tools (other tools: Context API, Recoil, Hooks, etc).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PU4JZiIhJ6QK4vokb5QDCg.png" /></figure><p><strong><em>Why do we need this? Why Redux?</em></strong></p><p>Well, let’s take an example of an application, with multiple components, to justify what Redux actually solves to make it clear why we need redux.</p><p>Consider, that each component manages its state and also has child components. Under some situations, we might need to share a state with a child component or we might need to change/update a state of a component from a child component.</p><p>That’s where we get into trouble. As our application grows to a higher number of components, state management can become a real challenge. It’s not an easy task to manage each component’s state while sharing it with many other components. We’re likely to experience data inconsistency bugs and that’s where <strong><em>“Redux”</em></strong> comes into play.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JAWge61qDCWcoARlKgdNVQ.png" /></figure><p>As shown in the image, Redux takes away the responsibility from individual components to manage a state. Instead, we create a single store that handles our state management. On top of that, all communication regarding reading, updating, or creating data happens via the store. It prevents data inconsistency bugs from appearing. Moreover, components can listen to state changes to update the UI and avoid these data inconsistency bugs.</p><blockquote>Thus, in general, Redux allows us to manage our app’s state in a single place and keep changes in our app more predictable and traceable. Apart from that, better community support, state persistence on local storage, server-side rendering, and maintainability are some of the major reasons to choose Redux.</blockquote><p><em>That answers our </em><strong><em>WHYs</em></strong><em> and </em><strong><em>WHATs</em></strong><em>. Not let’s get into </em><strong><em>HOW?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQW4L0XMdX5kdeG_NEn9CQ.png" /></figure><p><strong><em>Let’s jump into the Redux Cycle to understand how it works.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P03pn9bySWl9JKEaq19MBQ.png" /></figure><p><strong><em>This is what the Redux cycle looks like:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WPiBXsdrZ3slnq6ufjhScA.png" /></figure><ol><li><em>Users interact with the interface and trigger an action</em></li><li><em>Action with/without payload is sent to a reducer using the dispatcher</em></li><li><em>Reducer checks if it handles the action and produces a new state based on the action and its payload, and thus updates the Store that contains the state.</em></li><li><em>UI renders again based on state changes received via the subscription method</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*pLfyU8uJ9eaL3Ywzr3JB-Q.png" /></figure><p><strong><em>What “Actions”, “Reducers” and “Store” actually are?</em></strong></p><blockquote>This must be confusing and to make it easier to understand let’s try to connect a familiar event/story with the working on Redux.</blockquote><p>Consider going to a bank with just one intention/action in mind: <strong>WITHDRAW_MONEY</strong>. When we reach the bank, we go to the Cashier and tell them our intention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NcPeaF0cX1FmtZP3Q3XulA.png" /></figure><p>Although it’s our own money and we know that banks have money in the vault, we don’t go into the bank vault to get our money. Things don’t work that way. We need to talk to the Cashier to help us follow a process for withdrawing our own money. The Cashier then enters some commands from their computer and then delivers the cash. That’s how it works.</p><h4>But, how is this related to Redux, and its working?</h4><p><strong><em>1) “Store” in Redux is similar to what the Vault is to the bank</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5d7aNh5s-rLkMyHRiSr7LQ.png" /></figure><p>Just like the bank vault keeps our money safe in the bank, the state of our application is kept safe by something called a <strong><em>store</em></strong>. So, the <strong><em>store</em></strong> keeps our “money” or <em>state</em> intact.</p><p><strong><em>This leads to the first Redux principle :</em></strong></p><blockquote>“<strong>Have a single source of truth:</strong> The state of the whole application is stored in an object tree within a single Redux store.”</blockquote><p><strong><em>2) Go to the bank with an “Action” in mind</em></strong></p><p>To get money from the bank, we have to go with an intent/action to withdraw money. Not only that, but we also need to follow due process to withdraw our money from the bank.</p><p>Similarly, no matter what you do in the application, if we have to update the state of our Redux application (like we do setState in React), we need to let Redux know about that with an <strong>“<em>action”</em></strong>. Redux also accounts for a due process to change/update the state of your application.</p><p><strong><em>Now, this leads to Redux principle #2 :</em></strong></p><blockquote><strong>“State” is read-only:</strong> The only way to change the state is to emit an action, an object describing what happened.</blockquote><p>If we are to represent our intention of going into the bank, i.e., withdrawing money, in a simple redux application, our intention/action to the bank may be represented by an object that looks like this :</p><pre>{<br> type: “WITHDRAW_MONEY”, <br> amount: “$10,000”<br>}</pre><p>In the context of a Redux application, this object is called <strong><em>action</em></strong>! It always has a <em>type</em> field that describes the action we want to perform. In this case, it is “<em>WITHDRAW_MONEY”</em>.</p><p>Whenever we need to change/update the <em>state</em> of your Redux application, you need to <em>dispatch an action</em>.</p><p><strong><em>3) “Reducer” in Redux is similar to what Cashier is to the Bank</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ighEvvbCjF7bQ3HXBaCWZg.png" /></figure><p>Just like in our example where we had action in our mind but we had to convey that action/intention to the Cashier who in turn communicated (or whatever) with the vault that holds all of the bank’s money. In redux, to update a state, we need to convey our <strong><em>“action”</em></strong><em> </em>to the<em> </em><strong><em>“reducer”</em> </strong>— our own cashier. This process of conveying our action to the reducer is called <strong><em>“dispatching an action”</em></strong>.</p><p>The reducer knows what to do. In this example, it will take your action to “<em>WITHDRAW_MONEY”</em> and ensure that you get your money.</p><p>In Redux terms, the money you spend (eg: amount: “$10,000”) is your state. So, your reducer knows what to do, and it always returns your new state after performing the action.</p><p><strong><em>And this leads to the last Redux principle :</em></strong></p><blockquote><strong>To specify how the state tree is transformed by actions, you write pure reducers</strong> i.e., reducers are pure function and pure function is a function which, given the same input, always returns the same output</blockquote><p>This means, that to update the state of our application (like we do with “<em>setState”</em> in React,) our actions must always be sent off (<em>dispatched</em>) to the reducers to get our new state.</p><p>Now we must have some idea of what the most important Redux actors are and how they work: the <strong><em>store</em></strong>, the <strong><em>reducer</em></strong>, and an <strong><em>action</em></strong>.</p><p><strong><em>And also, this sums up the three major principles of redux :</em></strong></p><blockquote><strong>Principles of Redux :</strong></blockquote><p><strong>1. Single source of truth:</strong></p><p>The state of your whole application is stored in an object tree within a single store. It means that there is only one place, which represents the state of an application and your UI consumes it.</p><p><strong>2. State is read-only:</strong></p><p>“State” is immutable. So, it cannot be modified. If any changes are required, a new object for the state is created.</p><p><strong>3. Changes are made with pure functions:</strong></p><p>The only place to manipulate data in Redux is the reducer functions. As the reducers are pure functions, they don’t manipulate the existing data. Instead, they create a new instance of the data with the required changes.</p><p>When an action is dispatched, a corresponding reducer is invoked, and a new state object is created based on the action performed.</p><p>So, that was all about the actions of redux which is how redux works. I hope this article was helpful to you.</p><p>Feedback is always appreciated 🙏</p><blockquote><strong>Major Reference: </strong><a href="https://ohansemmanuel.gumroad.com/l/Ocgbb"><strong>Understanding Redux #1</strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*nIieoCW88pMMe1OhyWxqUw.png" /><figcaption>Happy Coding !!!</figcaption></figure><p>Travel Nepal with Nomadic Kutumba ❤ ️<br>Find me on Instagram: <a href="https://www.instagram.com/nomadic_kutumba/">@nomadckutumba</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a50acfe38d" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/understanding-the-concept-of-redux-5a50acfe38d">Understanding the Concept of Redux</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concept of Synchronous & Asynchronous Programming in JavaScript — Part 2 [Callbacks and Promises]]]></title>
            <link>https://medium.com/@dilipthakur87/concept-of-synchronous-asynchronous-programming-in-javascript-part-2-callbacks-and-promises-eb61c4220b69?source=rss-2251464f02b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb61c4220b69</guid>
            <category><![CDATA[callback]]></category>
            <category><![CDATA[promise-chain]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[asynchronous-javascript]]></category>
            <category><![CDATA[callback-hell]]></category>
            <dc:creator><![CDATA[Dilip Thakur]]></dc:creator>
            <pubDate>Tue, 16 Jun 2020 11:05:13 GMT</pubDate>
            <atom:updated>2020-06-16T11:05:13.170Z</atom:updated>
            <content:encoded><![CDATA[<h4>Concept of Synchronous &amp; Asynchronous Programming in JavaScript — Part 2 [Callbacks and Promises]</h4><p>In <a href="https://medium.com/@dilipthakur87/concept-of-synchronous-asynchronous-programming-in-javascript-part-1-f970119a8d52"><strong><em>Part 1</em></strong></a><strong><em> </em></strong>of this article, I mentioned about the basics of Synchronous and Asynchronous Programming in JavaScript. I strongly recommend you to go through <a href="https://medium.com/@dilipthakur87/concept-of-synchronous-asynchronous-programming-in-javascript-part-1-f970119a8d52"><strong><em>Concept of Synchronous &amp; Asynchronous Programming in JavaScript — Part 1</em></strong></a><strong><em> </em></strong>if you are new or have any confusions regarding the basics.</p><blockquote>According to wikipedia: “Asynchrony in Computer Programming refers to the occurence of events independently of the main program flow and way to deal with such events.”</blockquote><p>In this part, we will be discussing about how Callbacks and Promises handles Asynchronous Tasks in JavaScript.</p><h4>Callbacks :</h4><p><em>We will be starting with the basics of </em><strong><em>Callbacks</em></strong><em>. I will try to cover the basics with the help of following examples :</em></p><pre>// add two numbers and return the double of the result</pre><pre>function addAndDouble(x, y) {<br>    return (x+y)*2<br>}</pre><pre>const result = addAndDouble(2,3)<br>console.log(&quot;Result = &quot;, result)</pre><p>Now let’s perform the same task using the concept of <strong>Callbacks</strong> .</p><p><em>Here’s what it would look like :</em></p><pre>/* add two numbers and return the double of the result using callbacks */</pre><pre>function makeDouble(num) {<br>    return num*2<br>}</pre><pre>function add(x, y, callback){<br>    const sum = x+y<br>    const result = callback(sum)<br>    console.log(&quot;Result = &quot;, result)<br>}</pre><pre>add(2, 3, makeDouble)<br></pre><p><em>Here, if we run any of the above example, we would get the same output :</em></p><pre>Result = 10</pre><p>Although the second example looks confusing, but both does the same thing. The only difference is , in second example we are using the concept of Callbacks . Being said that, let’s highlight some of the important concepts of JS regarding Callbacks based on what we did.</p><blockquote>As you can pass any string or number as argument to a function in JS, you can also pass a reference to a function as argument. When you do this, the function you are passing as an argument is called <strong>Callback Function </strong>and the function you are the passing the Callback Function to is called a <strong>Higher Order Function</strong>.</blockquote><p>In our example above, <strong>makeDouble() </strong>is a Callback Function which is being passed to<strong> </strong><strong>add() </strong>as an argument and thus<strong> </strong><strong>add() </strong>here is the Higher Order Function.</p><blockquote>The <strong>Callback Function</strong> is not run unless called by its containing. It is called back in the <strong>Higher Order Function</strong> that’s containing it. Hence the term <strong>“Callback Function”</strong> .</blockquote><p>Here in our example, the Callback Function i.e., makeDouble() is being called after the addition of x and y is executed.</p><p>What we can conclude from this is , <strong><em>“Callbacks are just the functions passed in as an argument which you want them to be called after some operation is done.”</em></strong></p><blockquote><strong>Note: Callbacks can be a named or anonymous function. Also, we can pass multiple parameters to the callback function depending on the function.</strong></blockquote><p>Now let’s move a step forward focusing on how Callback handles asynchronous tasks. For that, let’s create a situation that shows the necessity of Callbacks.</p><p><em>“I will be using </em><em>setTimeout() so as to resemble API Calls or any task that might take some time to be executed”</em></p><pre>const todos = [&quot;Todo1&quot; , &quot;Todo2&quot;]</pre><pre>function getTodos() {<br>    setTimeout(()=&gt;{<br>        todos.forEach((todo) =&gt; {<br>        console.log(todo)<br>        })<br>    },1000)<br>}</pre><pre>function addNewTodo(newTodo) {<br>    setTimeout(() =&gt; {<br>        todos.push(newTodo)<br>    }, 2000)<br>}</pre><pre>addNewTodo(&quot;Todo3&quot;)<br>getTodos()</pre><p><em>If you run this block of code, then to your surprise, even after placing </em><em>addNewTodo() before </em><em>getTodos(), the output will be :</em></p><pre>Todo1<br>Todo2</pre><p>Where is <strong>“Todo3”</strong> then ???</p><p>The reason that we don’t see “Todo3” in the output is, the addNewTodo() took longer that getTodos() to execute because of the time specified in setTimeout() . This is a likely situation one might face while doing asynchronous tasks. To handle such issues, we need Asynchronous Programming.</p><p><em>Callbacks are simple functions which are used to notify the calling instance when an asynchronous code block has been executed and the result is available</em>. So, let’s actually make this work using Callbacks which is one of a way to handle such issues while doing Asynchronous Tasks.</p><p>In this case, we want to add the new todo first and then list the todos so as to get the recently added todo as well. So, we will make getTodos() a Callback Function that needs to be executed after addNewTodo() finishes its tasks.</p><p><em>Here’s how it would look like :</em></p><pre>// using concept of Callback </pre><pre>const todos = [&quot;Todo1&quot; , &quot;Todo2&quot;]</pre><pre>function getTodos() {<br>    setTimeout(() =&gt; {<br>        todos.forEach((todo) =&gt; {<br>            console.log(todo)<br>        })<br>    },1000)<br>}</pre><pre>function addNewTodo(newTodo, callback) {<br>    setTimeout(() =&gt; {<br>        todos.push(newTodo)<br>        callback()<br>    }, 2000)<br>}</pre><pre>addNewTodo(&quot;Todo3&quot;, getTodos)</pre><p><em>If you run this now, you will get :</em></p><pre>Todo1<br>Todo2<br>Todo3</pre><p>We got our <strong>“Todo3”</strong> back, Yayyyyyyyyy !!!! <br>What actually happened here is, our callback function i.e., getTodos() waited 2 seconds while the new todo item was being added to the list before it’s execution thus giving the above output.</p><p>This is fairly simple, as all we need to do is pass in a function which we want to execute after the Asynchronous Operation is done. But the major problem introduced by this approach is when we want to do Multiple Asynchronous Calls that too sequentially. Or, what if we want to use the result to make another request sequentially ????</p><p><em>Well, it introduces what is popularly known as “</em><strong><em>Callback Hell</em></strong><em>” and would look somewhat like below :</em></p><pre>function addNewTodo(newTodo) {<br>    addDate(date){<br>        addLocation(location){<br>            addAlarm(alarm){<br>                ......<br>            }<br>        }<br>    }<br>}</pre><p>This will actually work but will be very hard to debug and maintain. This situation known as <strong>“Callback Hell”</strong> can arise while working with large sets and to resolve such challenges of Callbacks, <strong>Promises</strong> were introduced.</p><h4>Promises :</h4><p><em>“I </em><strong><em>Promise</em></strong><em> to do this whenever that is true. If it isn’t true, then I won’t”<br></em>Though it sounds like an If Statement, there’s a huge difference that you will find out after reading this post.</p><blockquote><strong>Promises</strong> are simply the best wrappers to asynchronous tasks. A Promise is used to handle the asynchronous result of an operation. With Promises, we can defer execution of a code block until an async request is completed. This way, other operations can keep running without interruption.</blockquote><p>Every Promise Constructor expects a function which has two parameters <strong><em>resolve</em></strong> and <strong><em>reject </em></strong>. <strong><em>resolve </em></strong>is called if the <strong>Promise</strong> is resolved successfully and <strong><em>reject </em></strong>is called if any error has occurred.</p><p><em>Let’s look into a simple example on how to create a Promise .</em></p><pre>// creating a promise using regular function</pre><pre>const promise = new Promise(function(resolve, reject) {<br>    // an api call or any async operation<br>})<br></pre><pre>// creating a promise using arrow function</pre><pre>const promise = new Promise((resolve, reject) =&gt; {<br>    // an api call or any async operation<br>})</pre><p>You can create a promise using the keyword Promise as mentioned above.</p><p>To know about it’s usage, let’s jump into another example .</p><pre>const success = true</pre><pre>// creating a promise<br>const promise = new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        if(success){<br>            resolve(&quot;It&#39;s a success&quot;)<br>        } else {<br>            reject(Error(&quot;Failed&quot;))<br>        }<br>    },3000)<br>})</pre><pre>// using the created promise<br>promise.then((result) =&gt; {<br>    console.log(&quot;Result = &quot;, result)<br>}).catch((error) =&gt; {<br>    console.log(&quot;Error = &quot;, error)<br>})</pre><p><em>Running the above example will yield the following output :</em></p><pre>Result = It&#39;s a success</pre><p>Also, if you alter the value of success to false , the reject() will be called hence giving the following output :</p><pre>Error = Error: Failed</pre><p>What this conveys is , .then() receives a function with an argument which is the <strong>resolve</strong> value of our Promise and .catch() receives the <strong>reject</strong> value of our Promise.</p><p>During all this process, you can notice how the [PromiseStatus] changes to “resolved” form “pending” after the completion of the task (either “resolved” or “rejected”). That’s how Promises handles the async tasks.</p><p>As a next step to clear the confusions regarding the implementation of Promises, we will redo the previous task, where we added a new todo and listed them, using Promises instead of Callbacks .</p><pre>const todos = [&quot;Todo1&quot; , &quot;Todo2&quot;]</pre><pre>function getTodos() {<br>    setTimeout(()=&gt;{<br>        todos.forEach((todo) =&gt; {<br>            console.log(todo)<br>        })<br>    },1000)<br>}</pre><pre>function addNewTodo(newTodo) {<br>    return new Promise((resolve, reject) =&gt; {<br>        setTimeout(() =&gt; {<br>            todos.push(newTodo)<br>            const error = false;<br>            <br>            if(!error) {<br>                resolve(&quot;Added Successfully&quot;)<br>            } else {<br>                reject(&quot;Something went wrong&quot;)<br>            }<br>        }, 2000)<br>    })<br>}</pre><pre>addNewTodo(&quot;Todo3&quot;).then((response) =&gt; {<br>    console.log(response)<br>    getTodos();<br>}).catch((error) =&gt; {<br>    console.log(&quot;Error = &quot;, error)<br>})</pre><p><em>And if you run the program, you will get the following output :</em></p><pre>Added Successfully<br>Todo1<br>Todo2<br>Todo3</pre><p>We can see the <strong>“Todo3” </strong>here as well.</p><p>That’s how we can convert a program that’s using Callback concept to use Promises to get the same result but with more elegant and maintainable code as compared to that while using Callbacks.</p><p>Lastly, taking about the solution to the Callback Hell problem, while having to execute two or more asynchronous operations based on the result of preceding Promises, we can always use the concept of <strong>Chaining Promises</strong>.</p><p>To show the usage of <strong>Chaining Promises, </strong>let’s redo our first ever example of this article (<em>add two numbers and return the double of the result</em>) using Promise. To resemble the current scenario, we will have two Promises, one to add 2 numbers and the other to double it. We will be chaining these two Promises together to get the output as expected.</p><p><em>Here’s how it’s done :</em></p><pre>/* use of promise chaining - while having to execute two or more asynchronous operations in sequence */</pre><pre>const add = (x, y) =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        const error = false;<br>        if(!error){<br>            resolve(x+y)<br>        }else{<br>            reject(&quot;Something went wrong&quot;)<br>        }<br>    })<br>}</pre><pre>const returnDouble = (sum) =&gt; {<br>    return Promise.resolve(sum*2)<br>}</pre><pre>add(2,3).then((value) =&gt; {<br>    return returnDouble(value)<br>}).then((result) =&gt; {<br>    console.log(&quot;Result = &quot;, result)<br>}).catch((error) =&gt; {<br>    console.log(&quot;Error : &quot;, error)<br>})</pre><p><em>The execution of above block of code will yield the following output :</em></p><pre>Result = 10</pre><p><em>This is exactly what we expected.</em></p><p><strong><em>That’s how Promises have made it more easy to write async code and avoid Callback Hell, but can we do better ??? Because, just like you might have been thinking, it still looks confusing, isn’t it ??<br></em></strong><strong><em>To that, I would say, Oh Yeah ! definitely with “Async and Await” about which I will be writing in the final part of this article, Part 3. So stay tuned for the final part which will be posted soon. </em></strong>😉 😉 😉</p><p><em>I really hope you enjoyed reading this article and it helped you to to understand the concept of </em><strong><em>Callbacks and Promises</em></strong><em>. I really look forward to hear from you guys regarding any improvement or queries you have. More than happy to take the comments and suggestions.</em> 🙂</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*nIieoCW88pMMe1OhyWxqUw.png" /><figcaption>Happy Coding !!!</figcaption></figure><blockquote>“Life is asynchronous. You need make promises to handle it better. And remember, you have better options as well — have patience. Await !!!!” 😉 😉 😉</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb61c4220b69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concept of Synchronous & Asynchronous Programming in JavaScript — Part 1]]></title>
            <link>https://medium.com/@dilipthakur87/concept-of-synchronous-asynchronous-programming-in-javascript-part-1-f970119a8d52?source=rss-2251464f02b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f970119a8d52</guid>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[synchronous]]></category>
            <category><![CDATA[settimeout]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Dilip Thakur]]></dc:creator>
            <pubDate>Sun, 07 Jun 2020 04:15:41 GMT</pubDate>
            <atom:updated>2020-06-16T11:14:10.750Z</atom:updated>
            <content:encoded><![CDATA[<h4>Concept of Synchronous &amp; Asynchronous Programming in JavaScript — Part 1</h4><blockquote>While doing JS, one of the concept that confuses many beginners to intermediate level developers is Asynchronous (‘Async’) programming. As it’s one of the most common concept in JavaScript, you need to have a strong understanding of it before diving into JavaScript.</blockquote><p>So, based on my research and findings, I decided to come up with an article on the Concept of Synchronous &amp; Asynchronous Programming in JavaScript which is divided into 3 parts covering the following concepts respectively :</p><ol><li><a href="https://medium.com/@dilipthakur87/concept-of-synchronous-asynchronous-programming-in-javascript-part-1-f970119a8d52">Basics of Synchronous and Asynchronous Programming in JavaScript</a></li><li><a href="https://medium.com/@dilipthakur87/concept-of-synchronous-asynchronous-programming-in-javascript-part-2-callbacks-and-promises-eb61c4220b69">Callbacks and Promises</a></li><li>Async Await</li></ol><p>In this part, we will be discussing about the first point on the list — Basics of Synchronous and Asynchronous Programming in JavaScript along with some interesting examples. I request you guys to practice the examples by yourselves as well for better understanding.</p><blockquote><strong>In general, Synchronous code can be defined as — “a bunch of statements in sequence.” i.e., each statement in the code is executed one after another from top to bottom until the last statement finishes the execution. Thus, each statement has to wait for the previous one to complete execution.</strong></blockquote><p><em>Let’s practice an example to visualize our statement:</em></p><pre>let a = 30<br>let b = 50</pre><pre>console.log(a)<br>console.log(b)</pre><p><em>The codes are executed sequentially and we get the following output:</em></p><pre>30<br>50</pre><p><em>Let’s jump into another example using synchronous functions;</em></p><pre>let a = function(){return 20}<br>let b = function(){return 30}</pre><pre>console.log(a())<br>console.log(b())</pre><p><em>If we run this block of code, we will get the following output:</em></p><pre>20<br>30</pre><p>What I wanna convey is no matter however complex the statement is, each statement will be executed from top to bottom i.e, sequentially. The function will be executed, and then the return value will be assigned and finally the next line will be executed. <strong><em>The first method can have like more than 1000 of lines inside it but still it will take all the time to execute the statements inside it and then only the assignment will occur. And all before the next line is executed.</em></strong> That’s the concept of Synchronous Programming and that’s what JavaScript is doing most of the time.</p><p>But consider a situation where we need to fetch some data from the server that can take some time based on the internet connection or data size or any other dependency. We can’t just freeze the UI during that period of execution. It’s not an instantaneous thing. <strong><em>That’s where Asynchronous Programming jumps in.</em></strong></p><p><em>Let’s look into an example using </em><em>setTimeout() which is a very basic example of </em><em>Asynchronous Programming:</em></p><pre>let a = 4<br>let b = 3</pre><pre>setTimeout(function() {<br>   console.log(&quot;Async Task 1&quot;)<br>}, 100)</pre><pre>console.log(a)</pre><pre>setTimeout(function() {<br>   console.log(&quot;Async Task 2&quot;)<br>}, 90)</pre><pre>console.log(b)</pre><p><em>The output to above block of code will be:</em></p><pre>4<br>3<br>Async Task 2<br>Async Task 1</pre><p>We can see that even though setTimeout() comes before, it prints at the last. That’s because setTimeout() takes 100ms to complete.</p><blockquote><strong>As an </strong><strong>Asynchronous method, it’s executed after all the synchronous tasks are executed despite the positions of the code blocks. So the concept is, if we use </strong><strong>Asynchronous Programming to execute non instantaneous tasks, the following task won’t have to wait for the preceding task’s completion to execute.</strong></blockquote><p>In above example, even if we set the delay time to 0 ms, we will notice a similar behavior since the Synchronous tasks are always executed before the Asynchronous tasks irrespective of the position. Following the completion of the Synchronous tasks, Asynchronous tasks are executed afterwards in an order respective to their execution time. If you notice the output, you can see that Async Task 2 is printed before Async Task 1 since the delay time of second setTimeout() is less than that of the first one.</p><p><strong><em>Note: I suggest everyone to run the above example altering the delay time and do some other tweaks to get a better understanding and a clear concept if you guys are still confused.</em></strong></p><blockquote><strong>Based on what we discussed, one last thing that can be confusing is the use of variables while using any forms of </strong><strong>Asynchronous function. During such cases, it’s mostly always better to pass the variables into that </strong><strong>Asynchronous function other than relying on them from outside the </strong><strong>Asynchronous function as they could be changed by rest of the program before that specific function/block is executed.</strong></blockquote><p><em>Let’s do one last example to be clear on what I am trying to convey.</em></p><pre>let a = 1<br>let b = 2</pre><pre>setTimeout(function() {<br>   console.log(&quot;Async Task a = &quot;, a)<br>}, 10)</pre><pre>a = 5 // change the value of a after setTimeout()</pre><pre>console.log(a)<br>console.log(b)</pre><p><em>If you run this block of code, we will get the following as the output:</em></p><pre>5<br>2<br>Async Task a = 5</pre><p>As you can see, even if a is assigned to another value after the setTimeout(), the output of setTimeout() is Async Task a = 5. This is because, as we discussed earlier, setTimeout() being an Asynchronous function by default, it’s executed after all other Synchronous tasks are executed sequentially irrespective of the time we set. That is, even if we set the delay time to0ms, we will observe the same behavior. So, the variable a is already set to 5 before the execution of setTimeout() resulting in above output.</p><p><strong><em>Finally, we can conclude that </em></strong><strong><em>Asynchronous Programming makes it easier to handle more than one thing at a time and makes it possible to express waiting for long-running actions without freezing the program during these actions.</em></strong></p><p><em>This is it for now. Hope it made easier for you to understand the core concept. Any suggestions regarding this article are highly appreciated as this is my first article ever. <br>Next part of this article is about Callbacks and Promises that made Asynchronous Programming easier. </em><a href="https://medium.com/@dilipthakur87/concept-of-synchronous-asynchronous-programming-in-javascript-part-2-callbacks-and-promises-eb61c4220b69"><em>Click here to go to the next part of this article: Part 2</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*c-Wz8dcjnMbYVw-00EsRLg.png" /><figcaption>Happy Coding !!!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f970119a8d52" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>