<?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 Kumarpawanm on Medium]]></title>
        <description><![CDATA[Stories by Kumarpawanm on Medium]]></description>
        <link>https://medium.com/@kumarpawanm8085?source=rss-583b262f5592------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*bcl4MDTLHd9neqMQ</url>
            <title>Stories by Kumarpawanm on Medium</title>
            <link>https://medium.com/@kumarpawanm8085?source=rss-583b262f5592------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:13:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kumarpawanm8085/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[Everything You Need to Know About Async JavaScript]]></title>
            <link>https://medium.com/@kumarpawanm8085/everything-you-need-to-know-about-async-javascript-fd087758a960?source=rss-583b262f5592------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd087758a960</guid>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[callback-hell]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[callback]]></category>
            <category><![CDATA[javascript-event-loop]]></category>
            <dc:creator><![CDATA[Kumarpawanm]]></dc:creator>
            <pubDate>Fri, 08 May 2026 11:27:02 GMT</pubDate>
            <atom:updated>2026-05-08T11:28:09.828Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CJcTWw2K7iWp75IpUwRCnw.png" /></figure><h4>Sync and Async In JS:</h4><p><strong>Sync (Synchronous</strong>)<strong>:</strong></p><p>In synchronous JavaScript, code executes line by line in sequence.<br>Each operation waits for the previous one to finish before executing.</p><p>This means:</p><ul><li>Tasks are dependent on execution order</li><li>One task can block the next task</li></ul><pre>console.log(&quot;Line 1&quot;);<br>console.log(&quot;Line 2&quot;);<br>console.log(&quot;Line 3&quot;);<br><br>/*<br>Output:<br>Line 1<br>Line 2<br>lIne 3<br>*/</pre><p><strong>Asyn (Asynchronous):</strong></p><p>In asynchronous JavaScript, some operations take time to complete, such as:</p><ul><li>API calls</li><li>Timers</li><li>File operations</li></ul><p>These operations do not block the main thread.<br> JavaScript continues executing the remaining code while the async task runs in the background.</p><p>This means:</p><ul><li>Later synchronous code may execute before async code finishes</li><li>The main thread remains non-blocking</li></ul><pre>console.log(&quot;Start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;Async Operation&quot;);<br>}, 2000);<br><br>console.log(&quot;End&quot;); // this line will execute before setTimeout<br><br>/*<br>Start<br>End <br>Async Operation<br>*/</pre><h4>How do we convert sync code to async code?</h4><p>We can convert ‘<strong>Synchronous</strong>’ code into ‘<strong>Asynchronous</strong>’ code by moving our code inside time-consuming operations</p><p>JavaScript provides asynchronous APIs such as:</p><ul><li>setTimeout()</li><li>setInterval()</li><li>fetch()</li><li>Promises</li><li>async/await</li><li>File system APIs (Node.js)</li></ul><p><strong><em>Synchronous Code</em></strong></p><pre>console.log(&#39;Start&#39;);<br>console.log(&#39;Make Me Async&#39;);<br>conole.log(&#39;End&#39;);<br><br>/*<br>Here, the code executes line by line synchronously.<br>Output:<br>Start<br>Make Me Async<br>End<br>*/<br></pre><p><strong>C<em>onverting Sync to Async Using setTimeout</em></strong></p><pre>console.log(&#39;Start&#39;);<br>setTimeout(() =&gt; {<br>  console.log(&#39;Make Me Async&#39;); // will be printed after 1 second<br>}, 1000)<br>conole.log(&#39;End&#39;);<br><br>/*<br>Now &quot;Make Me Async&quot; is scheduled asynchronously using setTimeout().<br>Output:<br>Start<br>End<br>Make Me Async<br>*/</pre><h4>Callback &amp; Callback Hell</h4><p><strong>Callback:</strong></p><p>A callback is a function that is passed as an argument to another function and is executed later when a specific task is completed.</p><pre>function calculator(num1, num2, callback) {<br><br>  return callback(num1, num2);<br><br>}<br><br>function addTwoNumbers(num1, num2) {<br><br>  return num1 + num2;<br><br>}<br><br>const result = calculator(2, 3, addTwoNumbers);<br><br>console.log(result); // Output: 5</pre><p><strong>What is Callback Hell?</strong></p><p>Callback Hell is a situation where deeply nested callbacks make asynchronous code hard to read and manage, causing the code to grow horizontally like a pyramid.</p><pre>loginUser(user, () =&gt; {<br><br>  getProfile(() =&gt; {<br><br>    getPosts(() =&gt; {<br><br>      getComments(() =&gt; {<br><br>        console.log(&quot;Done&quot;);<br><br>      });<br><br>    });<br><br>  });<br><br>});</pre><p><strong><em>Problems with Callback Hell</em></strong></p><ul><li>Poor readability</li><li>Difficult debugging</li><li>Hard maintenance</li><li>Complex error handling</li></ul><p><strong><em>Solution</em></strong></p><p>Callback Hell can be solved using:</p><ul><li>Promises with .then()</li><li>async/await</li></ul><pre>// Using Promises<br>loginUser(user)<br>  .then(getProfile)<br>  .then(getPosts)<br>  .then(getComments)<br>  .then(() =&gt; {<br>    console.log(&quot;Done&quot;);<br>  })<br>  .catch((err) =&gt; {<br>    console.log(err);<br>  });<br><br><br>// Using async/await<br>async function handleUser() {<br><br>  try {<br><br>    const profile = await loginUser(user);<br><br>    const posts = await getPosts(profile);<br><br>    const comments = await getComments(posts);<br><br>    console.log(&quot;Done&quot;);<br><br>  } catch (err) {<br><br>    console.log(err);<br><br>  }<br><br>} </pre><h4>Web Browser API’s</h4><p>Web APIs are features provided by the browser that allow JavaScript to perform operations that the JavaScript engine itself cannot do.</p><ul><li>create timers</li><li>make HTTP requests</li><li>access the DOM</li><li>handle user events</li></ul><p>These capabilities are provided by the browser through Web APIs.</p><p><strong><em>Common Web APIs</em></strong></p><ul><li>setTimeout()</li><li>setInterval()</li><li>fetch()</li><li>DOM APIs</li><li>Geolocation API</li><li>Local Storage API</li><li>WebSocket API</li></ul><p><strong><em>Code Examples</em></strong></p><pre><br>// setTimeout() <br>setTimeout(() =&gt; {<br>  console.log(&quot;Timer Completed&quot;);<br>}, 2000)<br><br><br>// setInterval()<br>let count = 1;<br><br>setInterval(() =&gt; {<br><br>  console.log(count);<br>  count++;<br><br>}, 1000);<br><br><br>// fetch()<br>fetch(&quot;https://dummy.api/data&quot;)<br>  .then((response) =&gt; response.json())<br>  .then((data) =&gt; {<br>    console.log(data);<br>  });<br><br>// DOM API<br>const button = document.getElementById(&quot;btn&quot;);<br><br>button.addEventListener(&quot;click&quot;, () =&gt; {<br>  console.log(&quot;Button Clicked!&quot;);<br>});<br></pre><h4>Promise</h4><p><strong>What is Promise?</strong></p><p>A Promise is a JavaScript object that represents the eventual completion or failure of an asynchronous operation and its resulting value.</p><p><strong><em>Promise States</em></strong></p><ul><li>pending: initial state</li><li>fulfilled: operation completed successfully</li><li>rejected: operation failed</li></ul><pre>const promise = new Promise((resolve, reject) =&gt; {<br><br>  let success = true;<br><br>  if (success) {<br>    resolve(&quot;Task completed&quot;);<br>  } else {<br>    reject(&quot;Task failed&quot;);<br>  }<br><br>});</pre><p><strong><em>Common Promise Methods</em></strong></p><p>.then() Handles successful result</p><p>.catch()Handles errors</p><p>.finally()Runs regardless of success/failure</p><p>Promise.resolve()Creates resolved promise</p><p>Promise.reject()Creates rejected promise</p><p>Promise.all()Waits for all promises</p><p>Promise.race()Returns first settled promise</p><p>Promise.allSettled()Waits for all promises regardless of result</p><p>Promise.any()Returns first fulfilled promise</p><p><strong><em>.then()</em></strong></p><pre>const promise = Promise.resolve(&quot;Success&quot;);<br><br>promise.then((data) =&gt; {<br>  console.log(data);<br>});</pre><p><strong><em>.catch()</em></strong></p><pre>const promise = Promise.reject(&quot;Something went wrong&quot;);<br><br>promise.catch((err) =&gt; {<br>  console.log(err);<br>});</pre><p><strong><em>.finally()</em></strong></p><pre>Promise.resolve(&quot;Done&quot;)<br>  .finally(() =&gt; {<br>    console.log(&quot;Cleanup completed&quot;);<br>  });</pre><p><strong><em>Promise.resolve()</em></strong></p><pre>Promise.resolve(100)<br>  .then((data) =&gt; {<br>    console.log(data);<br>  });</pre><p><strong><em>Promise.reject()</em></strong></p><pre>Promise.reject(&quot;Error occurred&quot;)<br>  .catch((err) =&gt; {<br>    console.log(err);<br>  });</pre><p><strong><em>Promise.all()</em></strong></p><pre>const p1 = Promise.resolve(&quot;A&quot;);<br>const p2 = Promise.resolve(&quot;B&quot;);<br><br>Promise.all([p1, p2])<br>  .then((data) =&gt; {<br>    console.log(data);<br>  });</pre><p><strong><em>Promise.race()</em></strong></p><pre>const p1 = new Promise((resolve) =&gt; {<br>  setTimeout(() =&gt; resolve(&quot;First&quot;), 1000);<br>});<br><br>const p2 = new Promise((resolve) =&gt; {<br>  setTimeout(() =&gt; resolve(&quot;Second&quot;), 2000);<br>});<br><br>Promise.race([p1, p2])<br>  .then((data) =&gt; {<br>    console.log(data);<br>  });</pre><p><strong><em>Promise.allSettled()</em></strong></p><pre>const p1 = Promise.resolve(&quot;Success&quot;);<br>const p2 = Promise.reject(&quot;Failed&quot;);<br><br>Promise.allSettled([p1, p2])<br>  .then((data) =&gt; {<br>    console.log(data);<br>  });</pre><p><strong><em>Promise.any()</em></strong></p><pre>const p1 = Promise.reject(&quot;Error&quot;);<br>const p2 = Promise.resolve(&quot;Success&quot;);<br><br>Promise.any([p1, p2])<br>  .then((data) =&gt; {<br>    console.log(data);<br>  });</pre><h4>Inversion of control</h4><p>Inversion of Control means transferring the control of execution from your code to another system, function, or framework.</p><p>In JavaScript, Inversion of Control commonly happens with callbacks.</p><pre>setTimeout(() =&gt; {<br>  console.log(&quot;Hello&quot;);<br>}, 1000);<br><br>/*<br>you are giving control of your callback to: setTimeout<br>you do not control when callback executes<br>browser controls execution timing<br>*/</pre><p><strong><em>Why IoC Can Become Problematic</em></strong></p><ul><li>callback may execute multiple times</li><li>callback may never execute</li><li>error handling becomes difficult</li><li>hard to trust external code</li></ul><pre>function fetchData(callback) {<br><br>  setTimeout(() =&gt; {<br><br>    callback(&quot;Data received&quot;);<br><br>  }, 2000);<br><br>}<br><br>fetchData((data) =&gt; {<br>  console.log(data);<br>});<br><br>/*<br>Here:<br>fetchData controls when callback runs<br>your callback execution depends on another function<br>*/</pre><p><strong><em>How Promises Solve This</em></strong></p><pre>fetchData()<br>  .then((data) =&gt; {<br>    console.log(data);<br>  });</pre><p>Promises guarantee:</p><ul><li>callback runs once</li><li>value cannot change unexpectedly</li><li>better error handling</li></ul><h4>Event Loop in JS</h4><p>The Event Loop is a mechanism in JavaScript that continuously monitors the Call Stack and task queues to manage asynchronous operations.</p><p><strong><em>Why Do We Need the Event Loop?</em></strong></p><p>JavaScript executes only one task at a time because it has:</p><ul><li>one Call Stack</li><li>one main thread</li></ul><p>But JavaScript also supports:</p><ul><li>timers</li><li>API calls</li><li>DOM events</li><li>promises</li></ul><p>The Event Loop coordinates the execution of asynchronous tasks by moving them from task queues to the Call Stack.</p><p><strong><em>Main Components</em></strong></p><p>callstack: Executes synchronous code</p><p>Web APIs: Handle async operations</p><p>Callback Queue: Stores macrotasks</p><p>Microtask Queue: Stores promise callbacks</p><p><strong><em>Code Example</em></strong></p><pre>console.log(&quot;Start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;Timer&quot;);<br>}, 0);<br><br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;Promise&quot;);<br>});<br><br>console.log(&quot;End&quot;);<br><br>/*<br>Output:<br>Start<br>End<br>Promise<br>Timer<br>*/<br><br>/*<br>*Step-by-Step Execution*<br><br>1. console.log(&quot;Start&quot;)<br>Runs immediately.<br>Output: Start<br><br>2. setTimeout()<br>Timer registered in Web APIs<br>Callback waits in Callback Queue later<br><br>3. Promise.then()<br>Promise callback goes into: Microtask Queue<br><br>4. console.log(&quot;End&quot;)<br>Runs immediately.<br>Output: End<br><br>5. Call Stack Becomes Empty<br>Now Event Loop starts checking queues.<br>Priority Order:<br>Microtask Queue<br>↓<br>Callback Queue<br><br>6. Promise Callback Executes<br>Output: Promise<br><br>7. setTimeout Callback Executes<br>Output: Timer<br><br>*/<br></pre><h4>Fetch API</h4><p><strong>What is Fetch API?</strong></p><p>fetch() is a Web API used to make HTTP requests in JavaScript.</p><p>It returns a Promise.</p><pre>fetch(url, options)<br>/*<br>url → API endpoint<br>options → request configuration<br>*/</pre><p><strong><em>Common HTTP Methods</em></strong></p><p>GETRetrieve data</p><p>POSTCreate data</p><p>PUTUpdate the entire resource</p><p>PATCHUpdate partial resource</p><p>DELETEDelete resource</p><p><strong><em>Code Examples</em></strong></p><p><strong><em>GET Request</em></strong></p><pre>fetch(&quot;https://jsonplaceholder.typicode.com/posts/1&quot;)<br>  .then((res) =&gt; res.json())<br>  .then((data) =&gt; {<br>    console.log(data);<br>  });</pre><p><strong><em>POST Request</em></strong></p><pre>fetch(&quot;https://jsonplaceholder.typicode.com/posts&quot;, {<br><br>  method: &quot;POST&quot;,<br><br>  headers: {<br>    &quot;Content-Type&quot;: &quot;application/json&quot;<br>  },<br><br>  body: JSON.stringify({<br>    title: &quot;JavaScript&quot;,<br>    body: &quot;Learning fetch API&quot;<br>  })<br><br>})<br>.then((res) =&gt; res.json())<br>.then((data) =&gt; {<br>  console.log(data);<br>});</pre><p><strong><em>PUT Request</em></strong></p><pre>fetch(&quot;https://jsonplaceholder.typicode.com/posts/1&quot;, {<br><br>  method: &quot;PUT&quot;,<br><br>  headers: {<br>    &quot;Content-Type&quot;: &quot;application/json&quot;<br>  },<br><br>  body: JSON.stringify({<br>    id: 1,<br>    title: &quot;Updated Title&quot;,<br>    body: &quot;Updated Body&quot;<br>  })<br><br>})<br>.then((res) =&gt; res.json())<br>.then((data) =&gt; {<br>  console.log(data);<br>});</pre><p><strong><em>DELETE Request</em></strong></p><pre>fetch(&quot;https://jsonplaceholder.typicode.com/posts/1&quot;, {<br><br>  method: &quot;DELETE&quot;<br><br>})<br>.then((res) =&gt; {<br>  console.log(&quot;Deleted Successfully&quot;);<br>});</pre><h4>Error Handling in Async Code</h4><p><strong>Error Handling with Callbacks</strong></p><pre><br>function findUserByUserName(userName, callback){<br>  <br>   setTimeout(() =&gt; {<br><br>    if (userName) {<br>      callback(null, &quot;User Data&quot;);<br>    } else {<br>      callback(new Error(&quot;Invalid user name!&quot;), null);<br>    }<br><br>  }, 1000);<br>}<br><br><br>findUserByUserName(&#39;user@gmail.com&#39;, (err, data) =&gt; {<br>  <br>  if (err) {<br>    console.log(err.message);<br>    return;<br>  }<br><br>  console.log(data);<br>})</pre><p><strong>Error Handling with Promises</strong></p><pre>const promise = new Promise((resolve, reject) =&gt; {<br><br>  const success = false;<br><br>  if (success) {<br>    resolve(&quot;Task Completed&quot;);<br>  } else {<br>    reject(new Error(&quot;Task Failed&quot;));<br>  }<br><br>});<br><br>promise<br>  .then((data) =&gt; {<br>    console.log(data);<br>  })<br>  .catch((err) =&gt; {<br>    console.log(err.message);<br>  });</pre><p><strong>Error Handling with async/await</strong></p><pre>async function getData() {<br><br>  try {<br><br>    const response = await fetch(&quot;https://invalid-url.com&quot;);<br><br>    const data = await response.json();<br><br>    console.log(data);<br><br>  } catch (err) {<br><br>    console.log(&quot;Error:&quot;, err.message);<br><br>  }<br><br>}<br><br>getData();</pre><p><strong>Error Handling inside setTimeout</strong></p><pre>setTimeout(function() {<br>    try {<br>        var result = JSON.parse(&quot;invalid json&quot;);<br>        console.log(result);<br>    } catch (error) {<br>        console.error(&quot;Parsing failed:&quot;, error.message);<br>    }<br>}, 1000);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd087758a960" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>