<?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 Mahesh kumar gurjar on Medium]]></title>
        <description><![CDATA[Stories by Mahesh kumar gurjar on Medium]]></description>
        <link>https://medium.com/@mahesh94gurjar?source=rss-4300782469de------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*eGSWBJRsbuIWg_tk</url>
            <title>Stories by Mahesh kumar gurjar on Medium</title>
            <link>https://medium.com/@mahesh94gurjar?source=rss-4300782469de------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:36:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mahesh94gurjar/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[Mastering Asynchronous JavaScript In NodeJS: Callbacks, Promises, and Async/Await]]></title>
            <link>https://medium.com/@mahesh94gurjar/mastering-asynchronous-javascript-in-nodejs-callbacks-promises-and-async-await-17391649872a?source=rss-4300782469de------2</link>
            <guid isPermaLink="false">https://medium.com/p/17391649872a</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mahesh kumar gurjar]]></dc:creator>
            <pubDate>Sun, 05 May 2024 07:42:12 GMT</pubDate>
            <atom:updated>2024-05-05T16:29:10.116Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*a47fuCWo4puKZE9UIpUOkA.png" /></figure><h3>Table of Contents:</h3><ol><li><strong>Introduction</strong></li><li><strong>Callbacks in Node.js</strong></li><li><strong>Promises in Node.js</strong></li><li><strong>Async/Await with Node.js</strong></li><li><strong>Comparison and Best Practices</strong></li><li><strong>Conclusion</strong></li></ol><h3>Introduction:</h3><p>Asynchronous JavaScript is the groundwork for Node.js development in constructing scalable and “responsive” server-side applications. Through asynchronous programming, Node.js application processes can manage many tasks simultaneously without locking the execution thread, leading to better performance and responsiveness.</p><p>This article introduces the core concepts of callbacks, promises, and async/await as they relate to Node.js. Asynchronous programming is paramount in efficiently managing I/O operations, workload database queries, HTTP requests, and organizing comprehensive workflow in Node.js applications.</p><h3>1. Callbacks:</h3><p>What are callbacks?</p><blockquote>Callback functions are nothing but functions that can be called back after a certain task or code is executed. or you can say callback is a function which can be passed as an argument to another function.</blockquote><p>Callbacks are a foundational concept in Node.js for handling asynchronous operations. They allow you to specify what should happen after an asynchronous task is completed.</p><p>For example, after reading a file in Node.js using the fsmodule, you will need to process the content of that file after the file read is complete. You can wrap your processing logic in a single method and pass it as an argument to fs.readFile method.</p><pre>const fs = require(&#39;fs&#39;);<br>fs.readFile(&#39;example.txt&#39;, (err, data) =&gt; {<br>  if (err) {<br>    console.error(&#39;Error reading file:&#39;, err);<br>  } else {<br>    console.log(&#39;File content:&#39;, data.toString());<br>  }<br>});</pre><p>Callbacks are commonly used in Node.js APIs, but they can lead to callback hell when nested deeply. To avoid callback hell, we should consider using promises and async-await features.</p><h3>2. Promises in Node.js</h3><p>Promises provide a cleaner and more structured way to handle asynchronous tasks compared to callbacks. Node.js has built-in support for Promises, and many Node.js APIs now return Promises. Here’s an example of using Promises with the fs.readFile method:</p><pre>const { promisify } = require(&#39;util&#39;);<br><br>const fs = require(&#39;fs&#39;);<br><br><br><br>const readFileAsync = promisify(fs.readFile);<br><br><br><br>readFileAsync(&#39;example.txt&#39;)<br><br>  .then(data =&gt; {<br><br>    console.log(&#39;File content:&#39;, data.toString());<br><br>  })<br><br>  .catch(err =&gt; {<br><br>    console.error(&#39;Error reading file:&#39;, err);<br><br>  });<br><br></pre><p>Using util.promisify, we can convert callback-based functions into Promises, making them easier to work with.</p><h3>3. Async/Await with Node.js</h3><p>Async/Await is a modern JavaScript feature that allows you to write asynchronous code in a synchronous style. It’s built on top of Promises and provides even cleaner syntax for handling asynchronous operations. Here’s how you can use Async/Await with the fs.readFile method:</p><pre>const { promisify } = require(&#39;util&#39;);<br><br>const fs = require(&#39;fs&#39;);<br><br>const readFileAsync = promisify(fs.readFile);<br><br>async function readFile() {<br><br>  try {<br><br>    const data = await readFileAsync(&#39;example.txt&#39;);<br><br>    console.log(&#39;File content:&#39;, data.toString());<br><br>  } catch (err) {<br><br>    console.error(&#39;Error reading file:&#39;, err);<br><br>  }<br><br>}<br><br>readFile();</pre><p>Async/Await simplifies error handling and makes asynchronous code more readable and maintainable.</p><h3>4. Comparison and Best Practices</h3><p><strong>Callbacks</strong>:</p><p>Pros:</p><ul><li>Simple and widely supported in Node.js.</li><li>Direct control over the flow of asynchronous operations.</li></ul><p>Cons:</p><ul><li>Can lead to callback hell when dealing with multiple nested asynchronous tasks.</li><li>Error handling can be cumbersome with nested callbacks.</li></ul><p><strong>Promises</strong>:</p><p>Pros:</p><ul><li>Provides a cleaner alternative to callbacks with better error handling.</li><li>Supports chaining and sequential execution of asynchronous tasks.</li></ul><p>Cons:</p><ul><li>Requires a good understanding of Promise chaining and error propagation.</li><li>Some legacy Node.js APIs still use callbacks.</li></ul><p><strong>Async/Await:</strong></p><p>Pros:</p><ul><li>Offers a synchronous-like syntax for writing asynchronous code, making it more readable.</li><li>Simplifies error handling with try/catch blocks.</li><li>Built on top of Promises, allowing easy integration with existing Promise-based code.</li></ul><p>Cons:</p><ul><li>Requires Node.js version 8 or higher to use Async/Await natively.</li><li>Async/Await can hide the asynchronous nature of operations, potentially leading to performance issues if not used carefully.</li></ul><h4>Best Practices for Asynchronous Programming in Node.js</h4><blockquote>Prefer Promises over Callbacks:</blockquote><ul><li>Whenever possible, use Promises or Promisify callback-based functions to improve code readability and error handling.</li></ul><blockquote>Avoid Callback Hell:</blockquote><ul><li>Refactor deeply nested callbacks into named functions or use Promise-based control flow libraries like async or bluebird.</li></ul><blockquote>Use Async/Await for Sequential Code:</blockquote><ul><li>Use Async/Await for writing sequential, readable code that handles asynchronous operations elegantly.</li></ul><blockquote>Handle Errors Properly:</blockquote><ul><li>Always include error handling in asynchronous functions to catch and handle exceptions gracefully.</li><li>Use try/catch blocks with Async/Await for effective error handling.</li></ul><blockquote>Know When to Use Each Approach:</blockquote><ul><li>Understand the strengths and weaknesses of callbacks, Promises, and Async/Await, and choose the appropriate approach based on the specific use case.</li></ul><h3>Conclusion</h3><p>Mastering asynchronous JavaScript techniques like callbacks, Promises, and Async/Await is essential for developing efficient and scalable Node.js applications. By understanding these concepts and applying best practices, developers can leverage the full power of asynchronous programming in Node.js.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17391649872a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Async IO in python]]></title>
            <link>https://medium.com/@mahesh94gurjar/introduction-to-async-io-in-python-72e1f1b14753?source=rss-4300782469de------2</link>
            <guid isPermaLink="false">https://medium.com/p/72e1f1b14753</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[asyncio]]></category>
            <dc:creator><![CDATA[Mahesh kumar gurjar]]></dc:creator>
            <pubDate>Thu, 09 Dec 2021 13:31:56 GMT</pubDate>
            <atom:updated>2021-12-09T13:31:56.555Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Asynchronous programming</strong> is a means of parallel programming in which a unit of work runs separately from the main application thread and notifies the calling thread of its completion, failure or progress. To understand benefits of asynchronous programming , let’s have a look at below comparison between synchronous vs asynchronous functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bo-0x6Me9ijrfxUFHnvh4g.png" /></figure><p>As you can see, asynchronous functions can handle more operations while it waits for IO resources to be ready.</p><h3>Async IO:</h3><p>Concurrency and parallelism are expansive subjects that are not easy to wade into. While this article focuses on async IO and its implementation in Python, it’s worth taking a minute to compare async IO to its counterparts in order to have context about how async IO fits into the larger, sometimes dizzying puzzle.</p><blockquote><strong>Parallelism</strong> consists of performing multiple operations at the same time. <strong>Multiprocessing</strong> is a means to effect parallelism, and it entails spreading tasks over a computer’s central processing units (CPUs, or cores). Multiprocessing is well-suited for CPU-bound tasks: tightly bound for loops and mathematical computations usually fall into this category.</blockquote><p><strong>Concurrency</strong> is a slightly broader term than parallelism. It suggests that multiple tasks have the ability to run in an overlapping manner. (There’s a saying that concurrency does not imply parallelism.)</p><p><strong>Threading</strong> is a concurrent execution model whereby multiple threads take turns executing tasks. One process can contain multiple threads.</p><p>What’s important to know about threading is that it’s better for IO-bound tasks. While a CPU-bound task is characterised by the computer’s cores continually working hard from start to finish, an IO-bound job is dominated by a lot of waiting on input/output to complete.</p><blockquote>concurrency encompasses both multiprocessing (ideal for CPU-bound tasks) and threading (suited for IO-bound tasks). Multiprocessing is a form of parallelism, with parallelism being a specific type (subset) of concurrency.</blockquote><p><strong>async IO</strong> is a single-threaded, single-process design. It has been said in other words that async IO gives a feeling of concurrency despite using a single thread in a single process. Coroutines (a central feature of async IO) can be scheduled concurrently, but they are not inherently concurrent.It is a style of concurrent programming, but it is not parallelism. It’s more closely aligned with threading than with multiprocessing but is very much distinct from both of these and is a standalone member in concurrency’s bag of tricks.</p><h3>The asyncio Package and async/await:</h3><ul><li><strong>asyncio</strong>: the Python package that provides a foundation and API for running and managing coroutines</li><li><strong>async/</strong><strong>await</strong>: two new python keywords that are used to define coroutines</li><li><strong>Coroutines: </strong>specialised generator functions are the heart of async IO in Python</li></ul><p>Let’s understand performance difference between synchronous and asynchronous versions of an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6319c3a7aead759dc15c0e5d20192c3/href">https://medium.com/media/f6319c3a7aead759dc15c0e5d20192c3/href</a></iframe><p>Output:</p><pre>One<br>Two<br>One<br>Two<br>One<br>Two<br>sync.py executed in 3.00 seconds</pre><p>This is synchronous version of a code where we are waiting for 1 second to complete a certain task, and we are calling same function 3 times.<br>If you see the output of above code , it will take around 3 seconds to complete all 3 tasks.<br>Let’s understand the problem here, every time we are waiting for IO task to complete , our process is waiting there doing nothing.It will invoke the second function only after first function is returned.</p><p>How can we solve this with <strong>asyncio ?</strong></p><p>let try same example with asynchronous programming</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84e9205d3d490a3b4b2b427ac375dfd8/href">https://medium.com/media/84e9205d3d490a3b4b2b427ac375dfd8/href</a></iframe><p>Output:</p><pre>One<br>One<br>One<br>Two<br>Two<br>Two<br>async.py executed in 1.00 seconds</pre><p>above code is doing the same things which we were doing with synchronous code but if you run this program , this will take only 1 second to complete all 3 functions calls. But if you look output carefully for both the executions, there is difference in order of our print statements.</p><p>The order of this output is the heart of async IO. Talking to each of the calls to count() is a single event loop, or coordinator. When each task reaches await asyncio.sleep(1), the function yells up to the event loop and gives control back to it, saying, “I’m going to be sleeping for 1 second. Go ahead and let something else meaningful be done in the meantime.”</p><h3>Conclusion:</h3><p>Now that you’ve seen a healthy dose of code, let’s step back for a minute and consider when async IO is an ideal option and how you can make the comparison to arrive at that conclusion or otherwise choose a different model of concurrency.</p><p>If you have multiple, fairly uniform CPU-bound tasks, multiprocessing should be an obvious choice.</p><p>The contest between async IO and threading is a little bit more direct.</p><p>Threading can lead to infamous impossible-to-trace bugs due to race conditions and memory usage.Threading also tends to scale less elegantly than async IO, because threads are a system resource with a finite availability. Creating thousands of threads will fail on many machines. Creating thousands of async IO tasks is completely feasible.</p><p>Async IO shines when you have multiple IO-bound tasks where the tasks would otherwise be dominated by blocking IO-bound wait time, such as:</p><ul><li>Network IO, whether your program is the server or the client side</li><li>Serverless designs, such as a peer-to-peer, multi-user network like a group chatroom</li><li>Read/write operations where you want to mimic a “fire-and-forget” style but worry less about holding a lock on whatever you’re reading and writing to</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72e1f1b14753" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>