<?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 Md. Motaher Hossain on Medium]]></title>
        <description><![CDATA[Stories by Md. Motaher Hossain on Medium]]></description>
        <link>https://medium.com/@motaher13?source=rss-195924f5a3dd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Md. Motaher Hossain on Medium</title>
            <link>https://medium.com/@motaher13?source=rss-195924f5a3dd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 11:41:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@motaher13/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[To Hell With Callback, Promise, Async-Await]]></title>
            <link>https://medium.com/@motaher13/to-hell-with-callback-promise-async-await-b68b9934de2e?source=rss-195924f5a3dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/b68b9934de2e</guid>
            <category><![CDATA[promises-in-javascript]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Md. Motaher Hossain]]></dc:creator>
            <pubDate>Fri, 08 Mar 2024 12:16:53 GMT</pubDate>
            <atom:updated>2025-01-27T15:15:21.340Z</atom:updated>
            <content:encoded><![CDATA[<p>Usually I work with JAVA, Because of my code base, in my brain the code execution process is always synchronous. I’m used to think in synchronous way. Time to time I send some work to another thread, but that also creates a separate path of synchronous code execution.</p><p>So, every time I try to write some JS code, I have to iterate through the whole concept of its asynchronous world . I have to wrap my head around the things like promise, async-await. and to reason myself why the hell i even need those. So, here is my step by step walk of why JS needs these stuff.</p><p>Note: It’s a note written to remind myself of the concepts. it’s messy, lacks a lot of explanations, and might got some terminology wrong (i’m not a JS guy). so please be kind to me and let me know what I should correct to improve.</p><blockquote><strong>Lets start with Asynchronous</strong></blockquote><p>JS is single threaded by default. So if you have a controller endpoint, which can be called by thousands of users at the same time, keeping rest of the users waiting while you read from database or file for one user isn’t an option. To handle that, an special database access method should be used, which will take the operation to a separate thread (managed by os, kind of) and release the main thread. This kind of function is called asynchronous function. A lot of asynchronous methods like file reader, or database access methods already exists in JS natively. they take 2 things</p><ol><li>parameters to work with</li><li>a function to call after the work is done, to pass down the result of work, to process further. they are called <strong>CallBackFunction</strong></li></ol><p>example</p><pre>const {readFile, writeFile} = require(&#39;fs&#39;)<br><br>console.log(&quot;start task&quot;)<br>readFile(&#39;./content/first.txt&#39;, &#39;utf8&#39;, (err, result)=&gt;{<br>    if(err){<br>        console.log(err)<br>        return<br>    }<br>    const first = result<br>    readFile(&#39;./content/second.txt&#39;, &#39;utf8&#39;, (err, result)=&gt;{<br>        if(err){<br>            console.log(err)<br>            return<br>        }<br>        const second = result<br>    <br>        writeFile(&#39;./content/result-async.txt&#39;,<br>        `here is the result: ${first}, ${second}`<br>        , (err, result)=&gt;{<br>            if(err){<br>                console.log(err)<br>                return<br>            }<br>            console.log(&quot;end task&quot;)<br>        })<br>    })<br>})<br>console.log(&quot;starting next task&quot;)</pre><p>Here, readFile, writeFile are Asynchronus methods provided by js. we passed functions inside them to handle the output of reads and writes. we first read the first.txt file, after that in callback second.txt, after that inside another call back wrote in result-async.txt file</p><p>as you can see we are passing callback inside callback, inside also that call back. it’s called <strong>Callback Hell</strong></p><blockquote><strong>Here comes Promise</strong></blockquote><p>to handle this kind of messy code, JS introduced a concept called Promise<strong>.</strong></p><p>A Promise is an object representing the eventual completion (or failure) of an asynchronous operation, and its resulting value. A promise can be in one of three states:</p><ul><li>Pending: The initial state; the operation has not completed yet.</li><li>Fulfilled: The operation completed successfully.</li><li>Rejected: The operation failed.</li></ul><p><strong>A promise in JavaScript starts executing immediately upon its creation</strong></p><pre>console.log(&#39;Before promise creation&#39;);<br>let pr = new Promise((resolve, reject) =&gt; {<br>  console.log(&#39;Promise executor starts executing immediately&#39;);<br>  setTimeout(() =&gt; {<br>    resolve(&#39;Resolved value&#39;);<br>    // reject(&#39;Rejected reason&#39;); // Uncomment to see rejection behavior<br>  }, 1000);<br>});<br>console.log(&#39;After promise creation&#39;);<br><br>// &quot;Before promise creation&quot;<br>// &quot;Promise executor starts executing immediately&quot;<br>// &quot;After promise creation&quot;</pre><p>In the example, After a delay of 1000 milliseconds, the promise will be resolved. or rejected if that path is chosen. ‘resolve’ and ‘reject’ are basically two callbacks which changes the state of promise. So, the ‘pr’ will hold a promise which is in fulfilled or rejected state. we can access the fulfilled state with ‘then’, and rejected state with ‘catch’, and receive the outputs of those states</p><pre>pr.then((value) =&gt; {<br>  console.log(value); <br>}).catch((error) =&gt; {<br>  console.error(error); <br>});<br><br>// resolved value</pre><p>we can create another promise inside ‘then’, which will be immediately executed, and the output will be available in the chained ‘then’. or if rejected, the error will be available on the first catch down the chain. this process is <strong>Promise Chaining</strong></p><pre>pr.then((value) =&gt; {<br>    console.log(value); <br>    new Promise((resolve, reject) =&gt; {<br>        setTimeout(() =&gt; {<br>        resolve(&#39;2nd promise resolved&#39;);<br>        }, 1000);<br>    });<br>  }).then((value) =&gt; {<br>    console.log(value); <br>  }).catch((error) =&gt; {<br>    console.error(error); <br>  });<br>  <br>  // resolved value<br>  // 2nd promise resolved</pre><p>we can convert the previous Read file example code and remove the callbacks with promise</p><pre>const fs = require(&#39;fs&#39;);<br>// Wrap readFile in a promise<br>const readFilePromise = (filePath, encoding) =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    fs.readFile(filePath, encoding, (err, result) =&gt; {<br>      if (err) reject(err);<br>      else resolve(result);<br>    });<br>  });<br>};<br><br>// Wrap writeFile in a promise<br>const writeFilePromise = (filePath, data) =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    fs.writeFile(filePath, data, (err) =&gt; {<br>      if (err) reject(err);<br>      else resolve();<br>    });<br>  });<br>};<br><br>// Using then() to handle the promises<br>readFilePromise(&#39;./content/first.txt&#39;, &#39;utf8&#39;)<br>  .then((firstResult) =&gt; {<br>    return readFilePromise(&#39;./content/second.txt&#39;, &#39;utf8&#39;).then((secondResult) =&gt; {<br>      return { first: firstResult, second: secondResult };<br>    });<br>  })<br>  .then((results) =&gt; {<br>    const { first, second } = results;<br>    return writeFilePromise(&#39;./content/result-async.txt&#39;, `here is the result: ${first}, ${second}`);<br>  })<br>  .then(() =&gt; {<br>    console.log(&quot;end task&quot;);<br>  })<br>  .catch((err) =&gt; {<br>    console.log(err);<br>  });<br>console.log(&quot;starting next task&quot;);</pre><p>But the code still not that much readable. Honestly, synchonus code blocks feels much easier to read. for this purpose JS introduced the following concept</p><blockquote><strong><em>ASYNC/AWAIT</em></strong></blockquote><p>These are some keywords to restructure the code to avoid ‘then’ and ‘catch’</p><pre>async function process() {<br>    try {<br>        const first = await readFilePromise(&#39;./content/first.txt&#39;, &#39;utf8&#39;);<br>        const second = await readFilePromise(&#39;./content/second.txt&#39;, &#39;utf8&#39;);<br>        await writeFilePromise(&#39;./content/result-async.txt&#39;, `Here is the result: ${first}, ${second}`);<br>        console.log(&quot;end task&quot;);<br>    } catch (err) {<br>        console.error(err);<br>    }<br>    console.log(&quot;starting next task&quot;);<br>}<br><br>process()</pre><p>await gets put before a promise (readFilePromise() createss and resturns a promise) , it stops code execution until the promise is resolved, then passes the resolved value to the assigned variable. we can imagine the rest of the code as they are getting executed inside ‘then’ of the promise. in this example we’ve removed two ‘then’. any rejection will trigger the catch.</p><p>To use await the function must be marked with async. If you try to use await at the top level of your script or inside a function that is not marked as async, you will encounter a syntax error. why? This restriction is part of the language syntax to ensure that asynchronous operations are handled correctly and to make the code’s asynchronous nature explicit.</p><p>async also makes the function to return promise. If the function actually returns a value, it will be wrapped with a promise, and the promise will be resolved with that value. If the function throws an error, the promise will be rejected with that error.</p><p>with that, When you have an async method calling another async method, you&#39;re essentially chaining promises. The await keyword pauses the execution of the current async function until the promise returned by the called async function resolves.</p><pre>async function fetchData() {<br>    const data = await readFilePromise(&#39;./content/first.txt&#39;, &#39;utf8&#39;);<br>    return data;<br>}<br><br>async function processData() {<br>    // Wait for fetchData to complete and return its result<br>    const data = await fetchData();<br>    return `Processed ${data}`;<br>}<br><br>async function main() {<br>    try {<br>        const processedData = await processData();<br>        console.log(processedData);<br>    } catch (error) {<br>        console.error(&quot;An error occurred:&quot;, error);<br>    }<br>}<br><br>main();</pre><p>In this example:</p><ul><li>fetchData simulates an asynchronous data fetching operation.</li><li>processData waits for fetchData to complete using await and then processes the data.</li><li>main waits for processData to complete and logs the result (or catches errors if any occur).</li></ul><p>I hope that clarifies some concepts for you. Thank you!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b68b9934de2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>