<?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 Babak Gholamzadeh on Medium]]></title>
        <description><![CDATA[Stories by Babak Gholamzadeh on Medium]]></description>
        <link>https://medium.com/@babak.gholamzadeh92?source=rss-2704ea4c645------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fj8LaZNmnISQu2OsK0FcYQ.jpeg</url>
            <title>Stories by Babak Gholamzadeh on Medium</title>
            <link>https://medium.com/@babak.gholamzadeh92?source=rss-2704ea4c645------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 00:36:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@babak.gholamzadeh92/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[The benefit of the Thenable object in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/the-benefit-of-the-thenable-object-in-javascript-78107b697211?source=rss-2704ea4c645------2</link>
            <guid isPermaLink="false">https://medium.com/p/78107b697211</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[thenable]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[Babak Gholamzadeh]]></dc:creator>
            <pubDate>Mon, 11 Jan 2021 09:47:47 GMT</pubDate>
            <atom:updated>2021-01-11T09:47:47.201Z</atom:updated>
            <content:encoded><![CDATA[<p>The relation between thenable object, promise and async/await</p><figure><img alt="The benefit of thenable object in JavaScript" src="https://cdn-images-1.medium.com/max/700/1*x9GDjf2iPnSquG52Pcr5Ng.png" /></figure><p>If you use libraries like <a href="https://mongoosejs.com/"><strong>mongoose</strong></a>, <a href="http://knexjs.org/"><strong>knex</strong></a><strong> </strong>and some others similar to them — which has kind of chainable methods and also runs asynchronously — you should read this article too.</p><p>You might have already heard about thenable object, promise and async/await. If you haven’t or still didn’t get the relation between them, don’t worry we will cover that here completely.</p><h4>What is “thenable” object?</h4><p>The definition of thenable object is the simplest thing in the world:</p><blockquote>Any object that has a method named “then” is called a “thenable” object.</blockquote><p>For Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05876ed99517506b6068270f60cfea07/href">https://medium.com/media/05876ed99517506b6068270f60cfea07/href</a></iframe><p>This object (obj) is a thenable object.</p><p><em>Note: A </em><em>thenable object is allowed to have any other property and method with any name as well, but it must have a method is named </em><em>then to be a </em><em>thenable object.</em></p><h4>The relation between “thenable” object and “promise”?</h4><p>Simply <strong>every </strong><strong>promise object is just a </strong><strong>thenable object</strong>, because it has a then method (which is used to access the result of a <strong>settled</strong> promise). That’s it.</p><p>But keep in mind that this relation is not the other way around, which means that <strong>every </strong><strong>thenable object is not a </strong><strong>promise object</strong>.</p><h4>The relation between “thenable”, “promise” and “async/await”</h4><p>The then keyword is just a convention that has been defined to make life easier.</p><p>For instance, now we all know to access the result of a promise, we should call the then method of it. The name is not exec, run, get, map or anything else that causes confusion.</p><p>This naming convention has also helped us to have async/await syntax in JavaScript. But how?</p><p>Look that the code below and see the magic:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be45ad52aa321d459d20fdd317c93415/href">https://medium.com/media/be45ad52aa321d459d20fdd317c93415/href</a></iframe><p><em>If you are not familiar with IIFE function check this </em><a href="https://developer.mozilla.org/en-US/docs/Glossary/IIFE"><em>article</em></a><em>.</em></p><p>You probably have already used async/await syntax in your codes and know how to used it.</p><p>But do you also aware that how async/await works?</p><p>We are not going to fully cover the behind of the scene of async/await here. However, if you are curious about it (and you should be), you can check this <a href="https://medium.com/front-end-weekly/implement-the-async-await-pattern-and-be-familiar-with-the-generator-a04f5c6f4ee0">article</a> out to get the main idea of how it works.</p><h4>Brief explanation of how “async/await” works</h4><p>You should know that whenever you put an await keyword before any function (object), JavaScript just tries to call the then method of that object.</p><p>Also because async/await syntax is implemented by <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator">generator</a> function and await keyword is exactly used instead of yield keyword, so the async function needs to be resumed after calling the then method. In order to handle this operation, async function also sends a callback to the then method as a parameter that contains the functionality for resuming itself.</p><p>I know it sounds a little bit fuzzy and for getting the idea better, you should check out this sample code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53e82218ea899fb798e4a96ce2be2e6d/href">https://medium.com/media/53e82218ea899fb798e4a96ce2be2e6d/href</a></iframe><p><em>You can run this code and see the result yourself.</em></p><p>If you look at the output, you can see that almost everything works as expected. But we still don’t have the result of the last console.log(‘end’) and the operation is kind of freezing in that point.</p><p>The reason of this freezing is because the callback function which has been sent to the then method has not been called yet to resuming the async function.</p><p>In order to solve the problem, we should just call the callback to continue the operation.</p><p>Also if you send any value to the callback as its parameter, you will get it by the await keyword (see the code below):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1a88ab06c1ce7e6868c74eb92342edc/href">https://medium.com/media/b1a88ab06c1ce7e6868c74eb92342edc/href</a></iframe><p>And now everything worked perfectly.</p><h4>Main subject</h4><p>I guess till here you got the idea of what we are talking about and you might find out that how mongoose, knex and some other libraries work with some tweaking the code.</p><p>As a reminder, these libraries can be chainable and whenever you put an await keyword in behind of them or call the then method in their chain, they work exactly like a promise object.</p><p>In the following we are intending to walk through a simple example of a chainable object that would be ran by await keyword and/or then method.</p><p>The functionality that we expect from this stupid example that we are going to implement is to have some simple math methods (i.e. add, sub, mul, div) and whenever we use it with await keyword, it would run the main asynchronous operation and returns the corresponding result (which can be fulfilled or rejection).</p><p>The main asynchronous operation would be fulfilled if the reminder of the final value is divided by 2 be greater than zero — or not equal to zero (<em>n % 2 !== 0</em>) — and otherwise it would be rejected.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e4d247f24504e62f671794aebfecb3d/href">https://medium.com/media/1e4d247f24504e62f671794aebfecb3d/href</a></iframe><p>Now we have an asynchronous function, let’s implement another simple function which can be chainable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2af80b196ef254bfda1917647c05356a/href">https://medium.com/media/2af80b196ef254bfda1917647c05356a/href</a></iframe><blockquote>Note: I just refuse to use this keyword here to avoid confusion that some people might have with it.</blockquote><p>Now this function (mathOp) can be used in this way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce002828a9462fa01ecd00b5688b8391/href">https://medium.com/media/ce002828a9462fa01ecd00b5688b8391/href</a></iframe><p>It’s time to get to the main point and add the magical then method to this chainable object and run the asyncFunction inside of it. Afterward just return the result of it (which is a promise object).</p><p><em>Reminder: Don’t forget the callback function is going to be sent by </em><em>await keyword automatically.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bba6315111a5ba28b502e5e763d2e1d2/href">https://medium.com/media/bba6315111a5ba28b502e5e763d2e1d2/href</a></iframe><p>This is the whole implementation of the then method. It is simple, isn’t it?</p><p>Let’s put it inside the op object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99d78c77990946fb3116d205c3267ded/href">https://medium.com/media/99d78c77990946fb3116d205c3267ded/href</a></iframe><p>And now you can run the code below to see the result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f26a12b1cb135377a76b8d789cb190d/href">https://medium.com/media/4f26a12b1cb135377a76b8d789cb190d/href</a></iframe><p>Up until now it sounds that it works perfectly, but let me remind you that we didn’t handle the error that is caused by the rejection state of the asyncFunction.</p><p>First of all, to handle the errors, we need a catch method beside of the then method as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9c3ef7dd3fab19e3db351efd6870c77/href">https://medium.com/media/e9c3ef7dd3fab19e3db351efd6870c77/href</a></iframe><p>Put this method next to then method inside of op object.</p><p>There is nothing special about catch method and we just added it that we could use it on chaining methods ourselves — which works like then method on chaining and also send the callback to the catch method on the returned promise object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08ab02f9930c237092e1392db17d875f/href">https://medium.com/media/08ab02f9930c237092e1392db17d875f/href</a></iframe><p>In the next step for handling errors we need to tweak our then method.</p><p>If you wonder why we need to change the then method to handle the errors and what is the relation between them, let me tell you another secret of async/await.</p><p>I have to admit that I already lied to you about that await keyword that I said it just sends one callback on calling the then method, I’m sorry about that guys, because it sends two callbacks.</p><p>As a reminder we should mention that the then method on promise object takes two callbacks, but the second one is arbitrary which is used as a callback for catching errors — just like catch method.</p><p><em>If you are curious about how </em><em>promise works, you should check out this </em><a href="https://github.com/Babak-Gholamzadeh/Understanding-the-Core-Ideas-of-Promise-by-Implementing-it-in-JavaScript"><em>book</em></a><em>.</em></p><p>If you change the then method body like the code below, you would see the same output as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d570d53627e1b0e1104cc952c7db11c/href">https://medium.com/media/0d570d53627e1b0e1104cc952c7db11c/href</a></iframe><p>Great! Now we can also use mathOp function with await keyword inside of a try/catch block to handle the errors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f72cd2998e785cd7437f2d3f5758eb52/href">https://medium.com/media/f72cd2998e785cd7437f2d3f5758eb52/href</a></iframe><p>We are done with handling errors and the whole functionality of our stupid example.</p><p>At the end we can also do some fancy stuff to have a little cleaner code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/628c2af768051f43cd1c4c4ed83b48b5/href">https://medium.com/media/628c2af768051f43cd1c4c4ed83b48b5/href</a></iframe><h4>Wrapping up</h4><p>I hope you found this article useful.</p><p>If there is any unclear or ambiguous part, please feel free to ask your questions in the comment section or you can send me message directly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78107b697211" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-benefit-of-the-thenable-object-in-javascript-78107b697211">The benefit of the Thenable object in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement the Async/Await Pattern and be Familiar with the Generator]]></title>
            <link>https://medium.com/front-end-weekly/implement-the-async-await-pattern-and-be-familiar-with-the-generator-a04f5c6f4ee0?source=rss-2704ea4c645------2</link>
            <guid isPermaLink="false">https://medium.com/p/a04f5c6f4ee0</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[generator]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Babak Gholamzadeh]]></dc:creator>
            <pubDate>Fri, 08 May 2020 06:58:43 GMT</pubDate>
            <atom:updated>2020-05-08T15:37:38.867Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding the main ideas of this pattern by implementing it from scratch (in an evolutionary way)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wmF-Fnc_N9Z_17ODep2IPA.jpeg" /><figcaption>Photo by Andrea <a href="https://www.pexels.com/@olly?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong>Piacquadio</strong> </a>from <a href="https://www.pexels.com/photo/content-young-male-student-using-laptop-in-library-3771091/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong>Pexels</strong></a></figcaption></figure><p>If you came here and want to know more about <strong>async/await</strong> pattern, you probably have some experiences of using callbacks and had some struggles with callback hell(if you need to review some of the quirks about callbacks, you should check this <a href="https://medium.com/javascript-in-plain-english/the-practical-problems-with-callbacks-in-javascript-5dd4209c20d">article</a> out). Also, you might have some experiences of working with promise pattern.</p><p>Prerequisites for going further in this article is to have some ideas of how to use promise; but if you don’t, you’d better visit <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">this page on MDN</a> before continuing (and if you are really curious about the promise pattern and intend to fully understand it, you can read the book that I’ve published <a href="https://github.com/Babak-Gholamzadeh/Understanding-the-Core-Ideas-of-Promise-by-Implementing-it-in-JavaScript">here</a> for free).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff%2F788447%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2F788447%2F&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/18214d8333adbb5668f31791a3202b60/href">https://medium.com/media/18214d8333adbb5668f31791a3202b60/href</a></iframe><h3>Start from the past</h3><p>Let’s back to the days that there wasn’t any syntax for using async/await pattern to make the workflow of our codes clean and beautiful.</p><p>In those days, after adding promise natively in ES6 (aka ECMAScript 2015) and hanging around with this new pattern, we found that this pattern is really useful. It can solve many of the problems and struggles that we had with the ugly callback pattern and also makes our codes more readable.</p><blockquote>But as we all agree, nothing is perfect and everything can improve</blockquote><p>When we had started using promise instead of callbacks wherever possible, we saw that we still have to repeat the then method to run some sequences. There is still some boilerplate that is cumbersome to use.</p><p>On the other hand, it was kind of pain that we couldn’t access the variables in the previous then method scope unless we defined them globally (which is not a good idea).</p><p>And some of these sorts of excuses had bothered us.</p><p>Make a long store short, finally, we realized that we need something that makes our asynchronous workflow to look more synchronous. Because our mind is used to understand that structure better and feels more comfortable with that.</p><p>So to meet these needs, we started to analyze some ideas that came to our mind, and all of a sudden, we noticed that another <strong>cool and magical feature</strong> was added to JavaScript in ES6 as well.</p><p>And that was the <strong>generator</strong> function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*HUIZUwaq5Wkui0YGsB1xxA.jpeg" /><figcaption>The original photo by <a href="https://unsplash.com/@helloimnik?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Hello I’m Nik 🎞</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Let me introduce you to this unicorn</h3><p>The generator function has a weird and amazing structure somehow. It is the only function in JavaScript that its execution can be paused at a point and then be resumed again (actually I fell in love with it).</p><blockquote>Note: Here we are not going to deep dive into the generator function. We just want to get familiar with it to see some of its practical benefits that can help us to implement the async/await pattern.</blockquote><p>Let’s see its applications in an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8f641c6b455978442010082d5dd5010/href">https://medium.com/media/b8f641c6b455978442010082d5dd5010/href</a></iframe><p>As you can see, there are only two things in its syntax that we must mention:</p><ol><li>The asterisk (*) before the name of the function, defines that this function is a generator function. The asterisk just must be put between the function keyword and the name of the function (which is gen here). So all of these states are correct: function* gen, function *gen, function * gen, function*gen.</li><li>yield keyword that is the point that function will be paused there.</li></ol><p>The behavior of the generator function is different from other functions (make yourself ready to see some magic).</p><p>When you invoke this function by using gen(), the codes inside the function wouldn’t be executed immediately. By invoking that, it just returns an object (which is called a generator object) that has some methods on it. One of its most important methods is the next method.</p><p>At this point, by calling this next method we can run the gen function until we reach the first yield keyword and it would be paused there automatically.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c151c9a5f01dc8575bfdbb76a16097f/href">https://medium.com/media/8c151c9a5f01dc8575bfdbb76a16097f/href</a></iframe><p>When the execution be paused at that point, the value in front of the yield would be returned and it’s accessible by the next method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc2772fd3a3f91a9e5fa0f13f3aede41/href">https://medium.com/media/dc2772fd3a3f91a9e5fa0f13f3aede41/href</a></iframe><p>As you can see, the returned value of the next method is an object which has simply two properties.</p><ol><li><strong>Value</strong>: It is the value in the front of yield that be returned on each pause</li><li><strong>Done</strong>: It shows whether the execution of the gen function is done</li></ol><p>After you call the next method a few more times, you will get the below result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06cf2009d0499f998f3cd8d0159ab192/href">https://medium.com/media/06cf2009d0499f998f3cd8d0159ab192/href</a></iframe><p>After the third time that the next method be invoked — because there isn’t any yield keyword anymore — the execution of the gen function be done (which you can see in the done property) and also the value in the value property becomes undefined.</p><p>Actually, the last value is fed by the return statement, and because we don’t have any return keyword here, it is undefined (if a function doesn’t have any return keyword, JavaScript returns an undefined value from that function by default).</p><p>So far, we learned that a generator function can be paused at the position of a yield keyword and also returns the value that is in the front of the yield on each pause.</p><p>Another amazing thing that we can do is to pass an argument on each pause.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bd37cf6ed3ab21e4304c664a6f2c63e/href">https://medium.com/media/9bd37cf6ed3ab21e4304c664a6f2c63e/href</a></iframe><p>There is a point here that is important to keep in your mind; the argument of the first next method will be thrown away and by invoking that you are just able to get the returned value of the yield statement (I know it may sound weird at first, but as thinking about it more, it will make sense eventually).</p><p>But by invoking the second next method you can pass an argument to the first yield and execute the rest of the code until reaching the next yield statement (or a return keyword, or the end of the function).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c438db1a7741c2e062d08d46c587a726/href">https://medium.com/media/c438db1a7741c2e062d08d46c587a726/href</a></iframe><p>As you can see here we used a return statement in the gen function, then we got the returned value on calling the last next method.</p><p>The only two other things and we might need to know about the generator for this topic, are the return method and the throw method on the generator object.</p><p>Whenever these both methods be called — that doesn’t matter at each pause — the execution of the generator function would be stopped immediately no matter what.</p><p>The only difference between them is that when we use the return method, we just end the function normally and get an object like this { value: undefined, done: true } (the value property equals to the argument of the return method). But when we call the throw method, we end the function by throwing an exception.</p><h3>Let’s back to asynchronous stuff</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MxlTee-xc0wWDKD-hqDhjA.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@startup-stock-photos?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong>Startup Stock Photos</strong></a> from <a href="https://www.pexels.com/photo/whiteboard-sketching-design-planning-7366/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong>Pexels</strong></a></figcaption></figure><p>So far we have learned about some of the magical applications of the generator function. What if we use the generator for controlling the workflow of our asynchronous functions?</p><p>The idea is that we can use the generator to run the async functions and then <strong>pause </strong>until that function be resolved. The important thing about pausing with the generator is that it doesn’t block the program. Then it can be resumed again by the async function itself.</p><p>Let’s see the idea in the code to understand it better:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b0fe2d489dd42ce013cc6f69af90c2a/href">https://medium.com/media/0b0fe2d489dd42ce013cc6f69af90c2a/href</a></iframe><p>Until here, we called an asynchronous function in the front of the yield that returns a promise object. It means the returned value of calling the next method would be a promise object (unlike the previous examples that we returned just a simple value).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4ccccc479da589b56f36ce0c43b4298/href">https://medium.com/media/d4ccccc479da589b56f36ce0c43b4298/href</a></iframe><p>After this point, we can call the then method on the promiseObject because it’s just a normal promise that we used already.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d979be4b38c08acb18e68c422abc9979/href">https://medium.com/media/d979be4b38c08acb18e68c422abc9979/href</a></iframe><p>The key point here is that we called the next method inside the then method (which means after resolving the async function) and pass the resolved data to it as an argument.</p><p>This data will go back to the gen function and will be put inside the fetchedResult variable. Also the execution of the gen function will be resumed.</p><p>This code is kind of ugly, I know, but if you just take a closer look at the gen function, you can notice that we call an asynchronous function in a way that the workflow looks like synchronously somehow (of course it works asynchronously but the appearance of it is similar to synchronous codes).</p><p>I guess we got the idea at this point (if you didn’t, just try to play with the code or continue reading the article to eventually grasp it).</p><p>Before going further, let’s refactor this code to be more comfortable for adding features and some improvements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0dc1afba20e413b7b826273a8e2c4521/href">https://medium.com/media/0dc1afba20e413b7b826273a8e2c4521/href</a></iframe><p>This is exactly the previous code that we simply wrapped all the operations inside a function named asyncController and passed the generator function to it as an argument.</p><h3>Add features and improvements</h3><p>The first thing that we notice which needs improvement is that our asyncController function now can handle just one single async function and one pause. How about running a bunch of asynchronous functions one after each other?</p><p>We need some improvements in our asyncController to be able to handle a situation like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b0da05b47c099f66aef17301f205a41/href">https://medium.com/media/0b0da05b47c099f66aef17301f205a41/href</a></iframe><p>All the operations (i.e. fetchData, fetchedResult.json, saveData etc.) are asynchronous and we want them to be run respectively.</p><p>In order for the asyncController to handle this kind of situation, it just needs to repeat its operation until the last yield statement be resumed and the generator function is done.</p><p>But for implementing this iteration we cannot just use a simple loop (i.e. for(){}, while(){}, do{}while() etc.), because these sort of iterations are unpausable. We need a solution that we could control the flow of the iteration.</p><p>A way that comes to our mind is to use another function to run the operation and call it again whenever we want to repeat the operation for another yield statement.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78fc7509eccc1731fadca4c4f3b77e4f/href">https://medium.com/media/78fc7509eccc1731fadca4c4f3b77e4f/href</a></iframe><p>Except for the first line that we just get the generator object from the generator function, we put the rest of the codes inside another function named iterator, and call it for the first time.</p><p>Look inside the then method of the promiseObject — I just commented the previous code for you to see the change — we didn’t call the next method here, rather we called the iterator function recursively and send the data to it as an argument. The argument will be passed to the next method on the next round and this pattern will be repeated.</p><p>But wait! We forgot something here. How long is it going to iterate? Where is the base case of this recursive function?</p><p>We remember that the returned value of the next method is always an object which has two properties and one of them is the done property that tells us whether the generator function has been done.</p><p>Here we can use done property for the base case to terminate the iterator function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2e77343c9392e095bec42dc7a731a2d/href">https://medium.com/media/a2e77343c9392e095bec42dc7a731a2d/href</a></iframe><p>OK! This improvement is done! Let’s go to the next one.</p><p>The next thing that we ought to mention is that we all know whenever we use promise, it is wise to always add a catch method at the end of the chain.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab6b505fdbda57ae6954cdfac7f34ff4/href">https://medium.com/media/ab6b505fdbda57ae6954cdfac7f34ff4/href</a></iframe><p>So what do we suppose to do with the error that we catch here?</p><p>As we said before, the generator objects have another method named throw that is the best time to use it. We can throw the error to that method which would be handled inside the generator function.</p><p>You can call the throw method inside the catch method but in my opinion it’s better not to do that and call the iterator function again and then send the error to it. Because I think we should put all operations related to the generator object in one place (if you don’t like this approach, you can do that in your way. There might be plenty of ways to do that).</p><p>But if we send the data as well as the error in the same argument, how can the generator object recognize to run which method of itself?</p><p>Because for the errors it must call its throw method and then call its next method for the correct data.</p><p>Also, there are many ways to do that which is up to you to decide. Here we choose to send the name of the method that must be called, as another argument (which may not be the best way).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7274faa016dd583b8034ab600b148b8f/href">https://medium.com/media/7274faa016dd583b8034ab600b148b8f/href</a></iframe><p>Look at the code carefully. As you can see we pass the name of the method alongside the value (which can be the correct data or an error). Also we need to pass the next method name for the first time that we called the iterator function.</p><p>So now we pass the error to the generator function. But how is it going to be handled there?</p><p>Because the generator function runs synchronously, the errors that might occur there can be handled in a synchronous approach as well. Yep, I’m talking about try/catch blocks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a359fdf679de7db3a3dc8784b7c2d1f6/href">https://medium.com/media/a359fdf679de7db3a3dc8784b7c2d1f6/href</a></iframe><p>Oh! Look at this. It looks beautiful, doesn’t it?</p><p>But we’re not done yet, there are still some things we need to watch out. Let’s back to work.</p><p>By our implementation so far, the asyncController only enables us to handle async functions. But how about handling a simple value? What if someone put a string value in front of a yield statement?</p><p>Because we assume that everything is put in the front of a yield should return a promise object, it’s a good idea that we wrap any kind of value inside a promise before resolving.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf7e4af90f0f1827178d1d93fcb3606e/href">https://medium.com/media/bf7e4af90f0f1827178d1d93fcb3606e/href</a></iframe><p>By using the resolve static function on the Promise constructor, we can wrap any kind of value inside a promise object.</p><p>The next important thing which must be considered is that it is expected that our asyncController function should return a new promise object.</p><p>It makes our controller handier to be used with other workflows and the result of that be handled by another function. So returning a new promise object is a wise choice.</p><p>In order to return a promise object, you can use the resolve static function that we used before, or simply use the new keyword before the Promise constructor to create a new object and return that.</p><p>Let’s use the new keyword this time.</p><p>First let’s wrap everything inside the callback of the Promise constructor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ff7584ec062c72371bf9a5022fdb28a/href">https://medium.com/media/9ff7584ec062c72371bf9a5022fdb28a/href</a></iframe><p>Then the resolve and the reject functions should be used somewhere.</p><p>The resolve function must be called here because this line is the last thing that will be run if everything goes well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/065586eaa4054c0d3fe9302cd70aaee3/href">https://medium.com/media/065586eaa4054c0d3fe9302cd70aaee3/href</a></iframe><p>And the reject function must be called whenever that something goes wrong inside the generator function.</p><p>The only place that we can catch its error is when we call the methods on the generator object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b962ad372de55e1310cd6f649c463daa/href">https://medium.com/media/b962ad372de55e1310cd6f649c463daa/href</a></iframe><p>Let’s put it inside a try/catch and call the reject function in the catch block.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d70799cad35b0a4f8c655b440d54b8b/href">https://medium.com/media/0d70799cad35b0a4f8c655b440d54b8b/href</a></iframe><p>By returning a promise object, you are also able to add a then and a catch method after the asyncController function, or maybe use that inside another generator function which is wrapped by an asyncController.</p><p>We are done. This is kind of the implementation of the async/await pattern, that we just don’t have its syntax.</p><blockquote>Note: you can get the source code from <a href="https://github.com/Babak-Gholamzadeh/implement-async-await">here</a> which is also a much cleaner version of it.</blockquote><h3>Conclusion</h3><p>In this article we just focused on the understanding and implementation of the main concepts of the async/await pattern. definitely, this is not the exact implementation that is used to implement this pattern natively.</p><p>Here we intended to just talk about the ideas and concepts of this pattern and also get you familiar with the generator functions.</p><p>Now that you saw the underneath of these structures, maybe some thoughts might fly to your mind that could change everything and build some new patterns and structures which be used for some special cases.</p><p>Also fully understanding this kind of stuff can help you to understand the more complicated patterns.</p><p>As a programmer, do not distract your mind by some fancy names and tools. Your mission is to swim deep in the oceans of the programming concepts by your mind.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a04f5c6f4ee0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/implement-the-async-await-pattern-and-be-familiar-with-the-generator-a04f5c6f4ee0">Implement the Async/Await Pattern and be Familiar with the Generator</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Practical Problems with Callbacks in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/the-practical-problems-with-callbacks-in-javascript-5dd4209c20d?source=rss-2704ea4c645------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dd4209c20d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Babak Gholamzadeh]]></dc:creator>
            <pubDate>Sun, 26 Apr 2020 08:49:29 GMT</pubDate>
            <atom:updated>2020-04-30T11:16:57.321Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is wrong with nested callbacks and why everyone hates it?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IVTBhiH3FhYGfOwt" /><figcaption>Photo by <a href="https://unsplash.com/@clemono2?utm_source=medium&amp;utm_medium=referral">Clem Onojeghuo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As you might be new to JavaScript or use it for years, it’s kind of impossible that you have never heard of “<strong>Callback Hell</strong>” and the disgust around it. Somehow where ever you go, there is some guy who is saying <em>nested callbacks</em> is evil and shows an image like below and also the other guys usually say, “Callback Hell, Eek!”</p><figure><img alt="Callback hell in JavaScript" src="https://cdn-images-1.medium.com/max/1024/1*58vcVucp3Jn6HCnLalYlwQ.png" /><figcaption>Callback Hell — actually I think it looks cool :)</figcaption></figure><p>But as a novice (or an experienced guy) you might wonder what exactly is wrong with nested callbacks and why everyone hates it.</p><p>Perhaps you have heard some vague arguments about it, but let me try to clarify this subject and show some problems, which could help you to reason about callbacks logically and make you understand WHY you might need some other patterns (e.g., promises, async/await, observer, CSP, etc.)</p><h3>What is wrong with callback itself?</h3><p>First of all, let’s see what might happen when you use callbacks.</p><p>Let me tell you a true story.</p><p>A few months ago, I just wanted to use a function from a library that took a callback and passed the result as an argument to that callback (which is a norm for async functions) and I said, “OK, cool!”</p><p>But when I ran the program I noticed my callback was executed synchronously (Whaaat?? Why?)</p><p>If you write a function that suppose to work synchronously, why you want to pass the result to a callback? Why you just not return the value directly?</p><p>Actually, it’s not a good idea to use callbacks in this way and also there is no reason to do that (of course you can, but you shouldn’t) because <strong>it’s a convention that callbacks should be used in async functions</strong> or <strong>at least be called asynchronously</strong>.</p><p>I just told you this story to make it clear that when you send a callback to a third party, you have to rely on that party which may cause some disorders like the situations when the callback:</p><ul><li><strong>Would be called synchronously </strong>(like mine)</li><li><strong>Would be called multiple times</strong></li><li><strong>Would never be called</strong></li></ul><h3>What is wrong with nested callbacks?</h3><p>Before starting, let’s see why we put functions inside the callback of async functions (and this process can continue recursively if the put functions be asynchronous).</p><p>If you want to invoke some other functions after the execution of an async function, and because through callbacks are the only way that you can be noticed when an async function execution has been done, you have no choice except to put the next functions into the callbacks of the async function. (Like the image above.)</p><p>In other words, when we want to run some async functions in sequence, we have to fit them into the callbacks of the previous one, which makes nesting callbacks happen.</p><p>I hope the explanation till here is clear enough for you (if it’s not, ask your questions in the comment section and I will respond.)</p><p>Now we understood what causes nesting callbacks, let’s investigate the consequences of that.</p><h4>Error handling in nested callbacks</h4><p>You have probably heard about this argument, but we should peruse the problems with handling errors in nested callbacks together.</p><figure><img alt="Callback hell error handing in JavaScript" src="https://cdn-images-1.medium.com/max/1024/1*OVqGAIx11Mmz6JLKXmU2IQ.png" /><figcaption>Error handing in nested callbacks</figcaption></figure><p>As you can see, <strong>we have to handle error in every single callback</strong> and it’s actually a repetition of a boilerplate to handle errors. So <strong>this code is not DRY</strong> (we as programmers don’t like to repeat the same code over and over again) and it’s kind of difficult to reuse an error handler.</p><h4>Parallelism</h4><p>When we intend to use nested callbacks, there would be two possible relations between async functions:</p><ol><li>The async function executions must be in <strong>serial</strong></li><li>The async function executions should be in <strong>parallel</strong></li></ol><p>So let’s investigate both of them.</p><p><strong>The async function executions must be in serial</strong></p><p>For instance, imagine the situation when we want to read file-1 and then write the content in file-2.</p><figure><img alt="Callbacks run in serial" src="https://cdn-images-1.medium.com/max/1024/1*OzF4RHLGLNnjbIIRLpvlnw.png" /></figure><p>In this kind of situation they must run in serial and with this pattern, it can be done simply.</p><p><strong>The async function executions should be in parallel</strong></p><p>For instance, imagine the situation when we want to read file-1 and file-2, but just make sure that the content of file-1 be displayed before file-2’s.</p><figure><img alt="Callbacks run in serial" src="https://cdn-images-1.medium.com/max/1024/1*UIcCoZsTr11PUzNtdN-Ytg.png" /></figure><p>In fact, we have a problem here. It is right that the resolved contents must be displayed in sequence, but reading processes should be running at the same time (i.e., concurrent, parallel).</p><p>So it means we must not use nesting patterns, because it prevents us from being parallel. In other words, <strong>the nesting callback pattern is restricted to be run in serial</strong>.</p><p>In order to run these functions in parallel, we can use some tricks to achieve that:</p><figure><img alt="Callbacks run in parallel" src="https://cdn-images-1.medium.com/max/1024/1*EdJW21qDggmvVoOe5johnA.png" /><figcaption>Callbacks run concurrently, but the result of them would be displayed in sequence</figcaption></figure><p>In displayHandler function, we have to control the <strong>race condition</strong>.</p><blockquote>Note: race condition simply means when some async functions be resolved in incorrect sequence (e.g., file-2 be read before file-1)</blockquote><p>But these kind of tricks should not be used in production because they are neither scalable nor maintainable nor flexible.</p><h4>Reference to future value</h4><p>Last but not least, I’m going to mention a feature (in my opinion, we shouldn’t call it a problem) which cannot be achieved by the callback pattern.</p><p>We cannot pass a reference to the future value of an async function with callback pattern (unlike promise), we just can pass the control of execution of the async function.</p><h3>Wrapping up</h3><p>The main purpose of this article was to show you the problems in practical and tangible way.</p><p>The idea came to my mind that there might be some guys like me who cannot be convinced by some vague arguments about the problems with callbacks, such as “<em>callback hell is bad”, “it’s hard to reason about nesting”, “error handling is difficult”, </em>and these kind of stuff which were unclear to me back days.</p><p>So I tried to explain them from the perspective view of my personal experiences and the problems that I encountered them, in a simple way.</p><p>I hope you found this article useful (especially novices)</p><p>If there is anything unclear here, please feel free to ask your questions in the comment section, I will respond.</p><h4><strong>A note from JavaScript In Plain English</strong></h4><p>We have launched three new publications! Show some love for our new publications by following them: <a href="https://medium.com/ai-in-plain-english"><strong>AI in Plain English</strong></a>, <a href="https://medium.com/ux-in-plain-english"><strong>UX in Plain English</strong></a>, <a href="https://medium.com/python-in-plain-english"><strong>Python in Plain English</strong></a><strong> </strong>— thank you and keep learning!</p><p>We are also always interested in helping to promote quality content. If you have an article that you would like to submit to any of our publications, send us an email at <a href="/service/mailto:submissions@plainenglish.io"><strong>submissions@plainenglish.io</strong></a><strong> </strong>with your Medium username and we will get you added as a writer. Also let us know which publication/s you want to be added to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dd4209c20d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-practical-problems-with-callbacks-in-javascript-5dd4209c20d">The Practical Problems with Callbacks in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>