{"componentChunkName":"component---src-templates-blog-post-js","path":"/learn-to-handle-asynchronous-functions-in-javascript","result":{"data":{"contentfulBlogPost":{"createdAt":"2019-08-17T15:02:09.921Z","updatedAt":"2019-10-22T18:46:27.506Z","id":"bee7d960-0416-57b1-8f4c-d737bc25b3b3","description":"   Cómo se pronuncia One of the things that make JavaScript an impressive language is the ability to perform asynchronous tasks.","title":" Learn to handle asynchronous functions in JavaScript","body":{"id":"46b71256-c158-55f2-a2b8-c612be93f91e","childMarkdownRemark":{"id":"cc42c5b8-03ef-55ae-95c9-caca1c4c45e6","html":"<p>One of the things that make JavaScript an impressive language is the ability to perform asynchronous tasks. <strong>Asynchronous?</strong> Yes, JavaScript despite being a language that processes in a single thread <em>can continue its execution regardless of whether the previous function has not completed</em>.</p>\n<p>Not too fast, This capability is only possible with some functions. Let's look at a small example.</p>\n<pre><code class=\"language-javascript\">    function sum (x, y) {\n    console.log (x + y)\n    }\n    \n    setTimeout (function () {\n    sum (2,2)\n    }, 1000)\n    \n    sum (4.4)\n</code></pre>\n<p>Which of the two sums will be shown first? What is setTimeout? Why do I keep asking myself these questions? xd</p>\n<p>Ok, if you already despaired and tried on your browser console, you will have noticed that the <em>8</em> was shown first that <em>4</em>. This is because <strong>setTimeout</strong> is an asynchronous function that receives a function as the first parameter and the amount of milli seconds that function will be executed.</p>\n<p>But what if we change it to <em>0</em> the second setTimeout parameter?</p>\n<pre><code class=\"language-javascript\">function sum (x, y) {\nconsole.log (x + y)\n}\n\nsetTimeout (function () {\nsum (2,2)\n}, 0)\n\nsum (4.4)\n</code></pre>\n<p>Voila! We get the same result. How is this possible?</p>\n<h1>The magic of Event Loop</h1>\n<p>To understand how this whole concept works, we must take into account that JavaScript natively does not have things like setTimeout, but are APIs supplied by its execution environment such as * Browser * or others such as * Node.js *.</p>\n<p>The Event Loop, explained in a simplistic way, is the one in charge of handling the events that will be executed, according to their nature.\n<img src=\"https://miro.medium.com/max/700/1*s8PDSxizAIpw4B6Tdtd_Rg.png\"></p>\n<p>Describing what happens in the image:</p>\n<p>We see that the JavaScript environment is composed of:</p>\n<ul>\n<li><strong>The Memory Heap</strong>: which is the use of memory that uses language for its objects.</li>\n<li><strong>The Call Stack:</strong>: which is the stack where the context is accepted the code that is executed.</li>\n</ul>\n<p>Apart from this, we have the <strong>web API</strong> (* which can also be called the runtime API *). Also the <strong>Callback Queue or Queue</strong> which are the functions that will be processed.</p>\n<p>Finally, the <strong>Event Loop</strong> is responsible for moving the functions of the <em>Queue</em> to <em>Call Stack</em>.</p>\n<p>Let's see an example:</p>\n<pre><code class=\"language-javascript\">console.log (\"hello\")\n\nsetTimeout (timeout () function {\nconsole.log (\"world\")\n}, 5000)\n\nconsole.log (\"Ubykuo everywhere, everywhere\")\n</code></pre>\n<p><img src=\"https://medium.com/@ubykuo/event-loop-la-naturaleza-asincr%C3%B3nica-de-javascript-78d0a9a3e03d\" alt=\"loop\"></p>\n<blockquote>\n<p>We see that the timeout () function is processed by the <em>Web API</em>. After being completed, go to <em>Queue</em> so that the end is executed after you have already shown the last console.log.</p>\n</blockquote>\n<h1>Well... how do we handle it?</h1>\n<p>What happens if we need to wait or execute after an asynchronous function is completed?</p>\n<p>There are 2 ways to handle these types of situations. Although this section deserves its own post, we will show some of the ways in which these types of situations are handled.</p>\n<h2>Callbacks</h2>\n<p>Callbacks are functions that are passed as a parameter to be executed after certain operations.</p>\n<pre><code class=\"language-javascript\">function greet (name) {\nconsole.log (\"Hello\" + name)\n}\n\nfunction receive Invited Juan (callback) {\nguest var = \"Juan\"\ncallback (guest)\n}\n\nreceive Invited Juan (greet) // Hi Juan\n</code></pre>\n<p>Its use in asynchronous functions would be as follows:</p>\n<pre><code class=\"language-javascript\">function greet (name) {\nconsole.log (\"Hello\" + name)\n}\n\nfunction receive JuanMasTarde (callback) {\nsetTimeout (function () {\nguest var = \"Juan\"\ncallback (guest)\n}, 5000)\n}\n\nReceive JuanMasTarde (greet)\n// ... (Wait for 5 seconds)\n// Hello John\n</code></pre>\n<p>Although this form at first glance seems simple, it can be affected when many functions need to be nested, this problem is called <a href=\"http://callbackhell.com/\">Callbacks Hell</a></p>\n<h2>Promises</h2>\n<p>Promise or (Promise) is an object in JavaScript that represents a value that may or may not be available in the future. They were implemented to solve (in a better structured way) the asynchronous tasks that were performed with the Callbacks.</p>\n<p>The promises are created with the keyword '<em>new</em>' and passing a <strong>callback</strong> that receives two parameters that are also functions, which will be called if the operation was successful (<strong><em>resolve</em></strong>) and if something failed (<strong>*reject *</strong>).</p>\n<p>Let's see an example:</p>\n<pre><code class=\"language-javascript\">function addMasTardeShow (x, y) {\nvar newPromesa = new Promise (function (resolve, reject) {\nif (! x ||! y) {\nreject (\"Missing number\")\n}\n\nsetTimeout (function () {\nsolve (x + y)\n}, 1000)\n})\nreturn newPromise\n}\n\naddRead MoreShow (5.3)\n.then (function (result) {\nconsole.log (result)\n})\n.catch (function (error) {\nconsole.error (error)\n})\n</code></pre>\n<p>After we have this asynchronous function, we use <strong><em>then</em></strong> when we get the result and <strong><em>catch</em></strong> to capture the errors.</p>\n<p>The advantages of promises is that already many of the new asynchronous functionalities that are offered to the language, return a default promise. This is the case of <strong>fetch</strong>, which is provided by browsers to make <em>HTTP</em> requests.</p>\n<pre><code class=\"language-javascript\">const url = \"https://example.com/api/users\"\nconst body = {\n// ...\n}\n\nfetch (url, body)\n.then (function (response) {\nreturn response.json ()\n})\n.then (function (jsonResponse) {\nreturn console.log (jsonResponse)\n})\n.catch (function (error) {\nconsole.error (error)\n})\n</code></pre>\n<p>Here we see that in addition to <em>fetch</em> also <em>Body.json</em> uses promise. The latter is the object resulting from the request, which in turn uses this method to convert the JSON object response.</p>\n<h3>Async - Await</h3>\n<p>Finally, we have this method, introduced as standard in the ECMA 2017 specification. Like <strong>then</strong> and <strong>catch</strong> they work with Promise, only in a very particular way and making the syntax more readable.</p>\n<pre><code class=\"language-javascript\">function async getUsers () {\nconst url = \"https://example.com/api/users\"\nconst body = {\n// ...\n}\n\nconst response = await fetch (url, body)\nconst jsonResponse = await response.json ()\n}\n</code></pre>\n<p>The first thing to do is create a function with the keyword <strong>asycn</strong> in front. So we can use the <strong>await</strong> within this function. The <strong>await</strong> must be used before the sentence that will return the promise. So instead of getting the Promise object, we will get the expected value.</p>\n<h2>Conclusion</h2>\n<p>We must take into account that JavaScript has functions that will not return their value immediately and learn to use this behavior in our favor. Managing this knowledge gives us many alternatives and the possibility of using all language capabilities.</p>\n<p>What do you think?</p>","excerpt":"One of the things that make JavaScript an impressive language is the ability to perform asynchronous tasks. Asynchronous? Yes, JavaScript despite being a language that processes in a single thread can continue its execution regardless of whether the previous function has not…"}},"image":{"id":"e7e6d3a1-617f-5437-a9ea-e7df7f47a2f7","fluid":{"base64":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCAAUABQDASIAAhEBAxEB/8QAGAABAAMBAAAAAAAAAAAAAAAAAAUGBwj/xAArEAACAQMCBAMJAAAAAAAAAAABAgMABBEFIQcSMUEGE3EUIiMyQlGBscH/xAAXAQEBAQEAAAAAAAAAAAAAAAABAwQF/8QAIBEAAgIBAwUAAAAAAAAAAAAAAQIAESEDElETIjFhwf/aAAwDAQACEQMRAD8A7uXU7M2fIYoiyuVM3OQSR264qhcMuLulcSI9faOC408aZdGBTPyHzl+l9mOAcHY7jaq22szFAAOm7fz91nfCKTU7Bta9rtUhEc6Wi+XHCnOYyxJ+GBzfOPefLHudquzuHUKMG7+ThKNPptvHdiuPd8zp97iMMQ0iBh1GQMUrJDrEjklkz9vSlW3TPtmOt4v1Ozv7qRZ+czFSVkGVXCgYUdh39Sai/DnEjU9MurhRBaXCz6pMZFmjbceUxxswxuAdt9hvjIKlKjIi5NGSsPErVr5p3KW0IEzqEjjOAAxwNyTt0/FKUobzAHE//9k=","aspectRatio":0.9967320261437909,"src":"//images.ctfassets.net/szbztvipepx3/rOe6e2pNfOYxYaE9BxyGv/7c611a859072cb1abf1a286a4f1426f3/asyncfunction.jpg?w=786&q=50","srcSet":"//images.ctfassets.net/szbztvipepx3/rOe6e2pNfOYxYaE9BxyGv/7c611a859072cb1abf1a286a4f1426f3/asyncfunction.jpg?w=197&h=198&q=50 197w,\n//images.ctfassets.net/szbztvipepx3/rOe6e2pNfOYxYaE9BxyGv/7c611a859072cb1abf1a286a4f1426f3/asyncfunction.jpg?w=393&h=394&q=50 393w,\n//images.ctfassets.net/szbztvipepx3/rOe6e2pNfOYxYaE9BxyGv/7c611a859072cb1abf1a286a4f1426f3/asyncfunction.jpg?w=610&h=612&q=50 610w","srcWebp":"//images.ctfassets.net/szbztvipepx3/rOe6e2pNfOYxYaE9BxyGv/7c611a859072cb1abf1a286a4f1426f3/asyncfunction.jpg?w=786&q=50&fm=webp","srcSetWebp":"//images.ctfassets.net/szbztvipepx3/rOe6e2pNfOYxYaE9BxyGv/7c611a859072cb1abf1a286a4f1426f3/asyncfunction.jpg?w=197&h=198&q=50&fm=webp 197w,\n//images.ctfassets.net/szbztvipepx3/rOe6e2pNfOYxYaE9BxyGv/7c611a859072cb1abf1a286a4f1426f3/asyncfunction.jpg?w=393&h=394&q=50&fm=webp 393w,\n//images.ctfassets.net/szbztvipepx3/rOe6e2pNfOYxYaE9BxyGv/7c611a859072cb1abf1a286a4f1426f3/asyncfunction.jpg?w=610&h=612&q=50&fm=webp 610w","sizes":"(max-width: 786px) 100vw, 786px"}}}},"pageContext":{"slug":"learn-to-handle-asynchronous-functions-in-javascript","intl":{"language":"en","languages":["en","es"],"messages":{"title":"Omar Gaston","navbar.knowme":"About me","navbar.projects":"Projects","navbar.contact":"Contacts","frontpage.readMyBlog":"Read my blog","frontpage.knowme":"Who am I?","blog.subtitle":"Creating stories.","blog.title":"Sharing my ideas","blog.text":"with the community.","subscribe":"Subscribe","changeLanguage":"ES","goBack":"Go back","viewOnGithub":"View on Github","viewProject":"View Project","viewMore":"See more","notFound.title":"NOT FOUND","notFound.text":"You just hit a route that doesn't exist... what sadness! ","notFound.knowAuthor":"well, this guy","notFound.goBlog":"Better go and read something","notFound.whoSay":"...Who say that?","personal.title":"Who I Am?","personal.fullname":"Omar Gaston Chalas","personal.salute":"Hi, I'm","personal.presentation":"A Javascript Full-Stack Developer, Lover of creating products which make people's life easier.","personal.presentationContinue":"I'm always eager to hear about new ideas, create and learn new things.","personal.coverletter":"Well I'm Omar, a Dominican Software Engineer passionate about Javascript, web development and related technologies. As a developer, I've been building highly scalable business apps for more than 3+ years caring deeply about the details in both well-crafted code and user-facing experience. ","personal.coverletterContinue":"Since I remember, I've always been curious and eager to learn new technologies and acquire new skills. Constant learning and a proactivity attitude have allowed me to be comfortable with the rapid changes which are already common in the modern tech industry.","personal.coverletterContinue2":"Despite I care about keeping my technical skills shaped, I also have a Startup mindset and pragmatic attitude, that comes with a willingness to lead projects and desire to understand about the business and where it’s heading","personal.quote":"It's not all about me, As a team player, I love collaborating with others and be involved in Open Source projects. For me, mentoring and helping others is the best way to giving back to those whos have led me in the past.","personal.coverletterFooter":"By the way, These are some of the tools I'm currently using: ","aptitudes.title":"Skills","aptitudes.creativity.title":"Creativity","aptitudes.creativity.text":"The best way to demonstrate authenticity is by being creative.","aptitudes.innovation.title":"Innovation","aptitudes.innovation.text":"Experiment and apply new technologies.","aptitudes.focused.title":"Focus","aptitudes.focused.text":"The correct solutions arise by dividing a problem and focusing on each part.","aptitudes.consistency.title":"Consistency","aptitudes.consistency.text":"The only way to achieve success is to persevere.","aptitudes.simplest.title":"Simplicity","aptitudes.simplest.text":"It's always good when something works, but when it's simple and works, it's wonderful.","aptitudes.community.title":"♥","aptitudes.community.text":"Work as a team with communities and colleagues.","projects.title":"Projects","projects.text":"Some of the projects I've been working on","contact.title":"Contact","contact.text":"Talk to me and work together.","contact.form.email.label":"Email","contact.form.email.placeholder":"Your email","contact.form.message.label":"Message","contact.form.message.placeholder":"Anything about you, your work or your pet :)","contact.form.submit":"Send","contact.form.secondmessage":"Tell me, what's going on?","contact.writeme":"Write me!","lastPost.title":"Latest posts","search.result":"result","search.noresult":"No results for","search.search":"Search"},"routed":false,"originalPath":"/learn-to-handle-asynchronous-functions-in-javascript","redirect":false}}}}