{"id":2665,"date":"2018-03-28T15:01:12","date_gmt":"2018-03-28T15:01:12","guid":{"rendered":"https:\/\/solutionstreet.com\/blog\/?p=2665"},"modified":"2018-03-28T15:01:12","modified_gmt":"2018-03-28T15:01:12","slug":"its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript","status":"publish","type":"post","link":"https:\/\/www.solutionstreet.com\/blog\/2018\/03\/28\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\/","title":{"rendered":"It&#8217;s Getting Better All The Time &#8211; Making the Complex Simple Using Async\/Await in JavaScript"},"content":{"rendered":"<p><a href=\"https:\/\/solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/guitarguytitle2.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-medium wp-image-2672\" src=\"https:\/\/solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/guitarguytitle2-300x187.png\" alt=\"guitarguytitle2\" width=\"600\" height=\"374\" srcset=\"https:\/\/www.solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/guitarguytitle2-300x187.png 300w, https:\/\/www.solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/guitarguytitle2.png 507w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/a><\/p>\n<p>&nbsp;<\/p>\n<p>The famous line from a Beatles song also pertains to the JavaScript language. The JavaScript of years gone past in the late 90s has certainly come a long way from its early adoption. No one could have foreseen its rise to power and usage.  <\/p>\n<p>&nbsp;<\/p>\n<p>JavaScript seems to be everywhere nowadays including on the server with <a href=\"https:\/\/nodejs.org\/en\/about\/\" target=\"_blank\" rel=\"noopener\">Node.js<\/a>. I\u2019m fascinated with the potential of using one software language on both the client and the server. Clearly, JavaScript has won in every sense of the word on the client in that every popular front-end framework seems to be written in JavaScript. However, asynchronous coding on the client is still often difficult. On the server, here at Solution Street, we haven\u2019t seen as much interest in using Node.js as a server-side enterprise solution compared to the equivalent solutions found in Java, C#, Python, or Ruby. With <a href=\"http:\/\/callbackhell.com\/\" target=\"_blank\" rel=\"noopener\">callback hell<\/a> and the lack of simplistic sequential processing flow for our \u201cfor\u201d loops and \u201cif\u201d statements when making asynchronous calls, JavaScript may be a language not initially considered for complex server implementations or even ones with large quantities of business logic. However, with the support of <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/async_function\" target=\"_blank\" rel=\"noopener\">async\/await<\/a>, I believe that developers are now positioned and better equipped to use JavaScript on the server in larger numbers (and have an easier time on the client as well) that could lead to a spike in server-side JavaScript usage.<\/p>\n<p>&nbsp;<\/p>\n<p>In this article, we will walk through examples showing how asynchronous calls can be simplified with the inclusion of async\/await. These examples are front-end examples, but the same basic structure would apply on the server. First, before you go any further you must have a basic understanding of callbacks, Promises, and the event loop.  Here is an excellent explanation of <a href=\"http:\/\/exploringjs.com\/es6\/ch_async.html#ch_async\" target=\"_blank\" rel=\"noopener\">callbacks (and more)<\/a> and Promises, and here is an outstanding video on the <a href=\"https:\/\/vimeo.com\/96425312\" target=\"_blank\" rel=\"noopener\">event loop<\/a>.  Once you\u2019re up to speed, let\u2019s move on.<\/p>\n<p>&nbsp;<\/p>\n<p><a href=\"https:\/\/solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/callbackcrop-2.png\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/callbackcrop-2.png\" alt=\"callbackcrop (2)\" width=\"494\" height=\"181\" class=\"aligncenter size-full wp-image-2759\" srcset=\"https:\/\/www.solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/callbackcrop-2.png 494w, https:\/\/www.solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/callbackcrop-2-300x110.png 300w\" sizes=\"auto, (max-width: 494px) 100vw, 494px\" \/><\/a><\/p>\n<p>&nbsp;<\/p>\n<p>In general, with asynchronous calls we are typically dealing with file IO, database calls, or APIs. I may read a file and wait for the results. I may select data from the database and wait for the rows to be returned. I may call an external API and wait for the JSON to be returned. With respect to any of these possibilities, whether on the client or on the server, all of these are relatively the same when it comes to asynchronous interaction.  <\/p>\n<p>&nbsp;<\/p>\n<p>With <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/async_function\" target=\"_blank\" rel=\"noopener\">async\/await<\/a>, we can return to our more simplistic control flow structures in our code. Now we have the tools to simplify the complex and <a href=\"https:\/\/www.linkedin.com\/pulse\/write-less-code-arthur-frankel\/\" target=\"_blank\" rel=\"noopener\">write less code<\/a>. <\/p>\n<p>&nbsp;<\/p>\n<p>I\u2019d like to focus on what developers deal with the most in terms of what might be referred to as patterns or just general\/typical business logic and flow. Here is a list of six:<\/p>\n<p>&nbsp;<\/p>\n<ol>\n<li>Performing some basic asynchronous call (again this could be retrieving a list of data from the database or executing some RESTful API call).<\/li>\n<li>Performing the above (#1) several times in some chained\/sequential fashion &#8211; for example, first I get a customer record, then I get the list of accounts for that customer, and then I get a list of transactions for each account. Of course in database speak we would use a join on the server, but you can certainly envision cases where these are API calls where you have no control over the underlying details and you must make these three independent calls sequentially.<\/li>\n<li>Performing the above (#1) several times in some parallel fashion &#8211; for example, I can get financial transactions for different sets of accounts at the same time.<\/li>\n<li>For loops (and if conditions).<\/li>\n<li>Error handling (validation errors).<\/li>\n<li>Exception handling (something didn\u2019t go as planned with the call or connection).<\/li>\n<\/ol>\n<p>&nbsp;<\/p>\n<p>Before we start with the examples, let\u2019s discuss a few important points about async\/await:<\/p>\n<p>&nbsp;<\/p>\n<ul>\n<li>They look and feel like synchronous calls.<\/li>\n<\/ul>\n<ul>\n<li>They are supported in <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/New_in_JavaScript\/ECMAScript_Next_support_in_Mozilla#ECMAScript_2017\" target=\"_blank\" rel=\"noopener\">ES7 (ECMAScript 2017)<\/a>.<\/li>\n<\/ul>\n<ul>\n<li>They are <a href=\"https:\/\/caniuse.com\/#search=await\" target=\"_blank\" rel=\"noopener\">supported in the latest versions of most browsers<\/a> with the major exception of IE (<a href=\"https:\/\/medium.com\/@zwacky\/add-es7-async-await-support-into-your-non-bleeding-edge-build-process-ad0dded0d002\" target=\"_blank\" rel=\"noopener\">workaround<\/a>).<\/li>\n<\/ul>\n<ul>\n<li>They are <a href=\"http:\/\/node.green\/#ES2017\" target=\"_blank\" rel=\"noopener\">supported<\/a> in Node.js.<\/li>\n<\/ul>\n<ul>\n<li>Functions declared as async return a Promise (so you still need to understand Promises, which is a good thing). Await only works with Promises.<\/li>\n<\/ul>\n<ul>\n<li>Await can only be used inside of functions declared as async.<\/li>\n<\/ul>\n<ul>\n<li>They use simplified exception handling with try\/catch blocks.<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p><strong>Setup<\/strong><\/p>\n<p>&nbsp;<\/p>\n<p>In order to show understandable examples, I created a node server on Heroku that contains some basic tables and RESTful APIs (<a href=\"https:\/\/github.com\/afrankel\/basichttp\" target=\"_blank\" rel=\"noopener\">github project<\/a>). I did this quickly using loopback.io. You can read <a href=\"https:\/\/solutionstreet.com\/blog\/javascript-server-apis-with-node-and-loopback-video\/#.WrhMLpPwb-Y\" target=\"_blank\" rel=\"noopener\">my article<\/a> on LoopBack or see <a href=\"https:\/\/www.youtube.com\/watch?v=kthQssL_vFk\" target=\"_blank\" rel=\"noopener\">my video<\/a> on how to do this yourself. I have established a basic parent->child->grandchild database table relationship using Customers, Accounts, and Transactions, respectively. <\/p>\n<p>&nbsp;<\/p>\n<p>Here are the <a href=\"https:\/\/floating-meadow-81947.herokuapp.com\/api\/Customers\" target=\"_blank\" rel=\"noopener\">list of Customers<\/a>; the <a href=\"https:\/\/floating-meadow-81947.herokuapp.com\/api\/Accounts\" target=\"_blank\" rel=\"noopener\">list of Accounts<\/a>; and the <a href=\"https:\/\/floating-meadow-81947.herokuapp.com\/api\/Transactions\" target=\"_blank\" rel=\"noopener\">list of Transactions<\/a>.<\/p>\n<p>&nbsp;<\/p>\n<p>Again, these are running on a node server on Heroku. The purpose of doing this is to have  typical endpoints where we are performing a database operation or similar which is consistent with a typical business application. By using three different endpoints we can display the complexity (and simplicity) of executing them in series and, if needed, in parallel. These examples are from a front-end perspective, but we could have easily showed the server logic performing similar calls or calls to a database.<\/p>\n<div style=\"padding: 12px; background-color: #eee9e9; line-height: 1.2; margin: 40px; border: 1px solid #ccc; border-radius: 6px; box-shadow: 1px #ccc; border-left: 5px solid #61963D;\"><span style=\"font-size: x-large; color: #61963d;\">\u201c<\/span><em>With the support of async\/await, I believe that developers are now positioned and better equipped to use JavaScript on the server in larger numbers (and have an easier time on the client as well) that could lead to a spike in server-side JavaScript usage.<\/em><span style=\"font-size: x-large; color: #61963d; line-height: 1.0;\">\u201d<\/span><\/div>\n<p><strong>Example 1 &#8211; Single Call<\/strong><\/p>\n<p>&nbsp;<\/p>\n<p>First, let\u2019s review a basic Promise example of making an HTTP request to our server (<a href=\"https:\/\/jsfiddle.net\/afrankel\/7htaqzja\/\" target=\"_blank\" rel=\"noopener\">jsfiddle version<\/a>). I am using a basic and commonly used Promise\/await capable library called <a href=\"https:\/\/github.com\/axios\/axios\" target=\"_blank\" rel=\"noopener\">axios<\/a>. Here we are calling to our node server to request the Customer with the ID of \u201c1\u201d. The complexity here isn\u2019t bad especially with basic Promise logic of using a \u201cthen\u201d clause after the call.<\/p>\n<p>&nbsp;<\/p>\n<pre lang=\"javascript\" line=\"1\">const axios = require(\"axios\");\nconst apiURL = 'https:\/\/floating-meadow-81947.herokuapp.com\/api'\n\n\/\/ Get customer record\nfunction getCustomer(custId) {\n return axios.get(apiURL + '\/Customers\/' + custId)\n .then(response => {\n   console.log(response.data);\n })\n .catch(error => {\n   console.log(error);\n })\n}\n\ngetCustomerAsync(1);\n<\/pre>\n<p>&nbsp;<\/p>\n<p>Now let\u2019s take a look at the async\/await example (<a href=\"https:\/\/jsfiddle.net\/afrankel\/2a3ema37\/\" target=\"_blank\" rel=\"noopener\">jsfiddle version<\/a>). Here we can see the code layout is different with a few obvious variations including: the use of the \u201casync\u201d keyword in the function declaration; the use of the \u201cawait\u201d keyword in the asynchronous call to axios; the use of a plain old try\/catch block; and then the somewhat obvious code pattern of a typical synchronous call flow (i.e., after the axios call, the flow of control goes to the next line which is a console.log statement).<\/p>\n<p>&nbsp;<\/p>\n<pre lang=\"javascript\" line=\"1\">const axios = require(\"axios\");\nconst apiURL = 'https:\/\/floating-meadow-81947.herokuapp.com\/api'\n\n\/\/ Get customer record\nasync function getCustomerAsync(custId) {\n try {\n   const response = await axios.get(apiURL + '\/Customers\/' + custId);\n   console.log(response.data);\n } catch (error) {\n   console.error(error);\n }\n}\n\ngetCustomerAsync(1);\n<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>Example 2 &#8211; Multiple Calls \/ Sequentially<\/strong><\/p>\n<p>&nbsp;<\/p>\n<p>Now that we have seen an example using the basic structure of an \u201cawait\u201d call, let\u2019s proceed into something more complex. Imagine that there are three calls in succession that need to be made. First, retrieve the customer record using an ID, then retrieve that customer\u2019s accounts, then retrieve the financial transactions for one of the accounts. Of course, if the API or database is under your control you would probably make a single call (e.g., join) but for the purposes of this example (e.g., black-box APIs) we will assume these are three separate calls.<\/p>\n<p>&nbsp;<\/p>\n<p>First, let\u2019s provide the basic code for our example.  This is a class that contains the methods to retrieve the Customer, Accounts, and Transactions, plus some helper functions [NOTE: Here we are using the Promise-like calls for axios, but as shown above, these calls could be made using the \u201cawait\u201d call structure.]:<\/p>\n<p>&nbsp;<\/p>\n<pre lang=\"javascript\" line=\"1\">const axios = require(\"axios\");\nconst apiURL = 'https:\/\/floating-meadow-81947.herokuapp.com\/api'\n\n\/\/ Simulation of a fictitious bank\n\/\/ Assuming that all of the processing occurs via a database or API\nclass SolutionStreetBank {\n\n \/\/ Get customer record\n getCustomer(custId) {\n   return axios.get(apiURL + '\/Customers\/' + custId)\n   .then(response => {\n     return response.data;\n   })\n   .catch(error => {\n     console.log(error);\n   })\n }\n\n \/\/ Get Accounts based on Customer ID\n getAccounts(custId) {\n   var self = this;\n   return axios.get(apiURL + '\/Accounts')\n   .then(response => {\n     \/\/ filter array results based on Customer ID\n     return self.filterResults(\n       custId, 'custId', response.data);\n   })\n   .catch(error => {\n     console.log(error);\n   });\n }\n\n \/\/ Get Transactions based on Account ID\n getTransactions(accountId) {\n   var self = this;\n   return axios.get(apiURL + '\/Transactions')\n   .then(response => {\n     \/\/ filter array results based on Account ID\n     return self.filterResults(\n       accountId, 'accountId', response.data);\n   })\n   .catch(error => {\n     console.log(error);\n   });\n }\n\n \/\/ Helper function to delay to request for demo purposes\n \/\/ if you want to delay a call 2 seconds for example use this\n \/\/ statement prior to a call:\n \/\/\n \/\/ return this.delay(2000).then(function() {\n \/\/ \n delay(time, value) {\n   return new Promise(function(resolve) {\n       setTimeout(resolve.bind(null, value), time)\n   });\n }\n\n \/\/ Helper function to return subset of array that matches id\n filterResults(id, idName, array) {\n   let returnArray = []\n   for( var i=0; i<array.length; i++) {\n     if(array[i][idName] === id) {\n       returnArray.push(array[i]);\n     }\n   }\n   return returnArray;\n }\n}\n<\/pre>\n<p>&nbsp;<\/p>\n<p>If we were to make use of this class by retrieving a Customer by ID, then their Accounts, then the Transactions for one of the accounts, we might use a function like this using standard callback structures (<a href=\"https:\/\/jsfiddle.net\/afrankel\/z44g0cyx\/\" target=\"_blank\" rel=\"noopener\">jsfiddle version<\/a>):<\/p>\n<p>&nbsp;<\/p>\n<pre lang=\"javascript\" line=\"1\">function getAllDataCallbackStyle() {\n \/\/ Promises but using callback functions\n let cust, accounts, transactions\n const bank = new SolutionStreetBank()\n console.log(\"getting customer...\");\n bank.getCustomer(1).then(function(response) {\n   cust = response;\n   console.log(\"getting accounts...\");\n   bank.getAccounts(cust.id).then(function(response) {\n     accounts = response\n     console.log(\"getting transactions...\");\n     \/\/ to simplify we'll just get transactions based on the first account\n     bank.getTransactions(accounts[0].id).then(function(response) {\n       transactions = response\n       console.log('getAllDataCallbackStyle\\n',\n         { cust, accounts, transactions })   \n     })\n   })\n })\n}\n\ngetAllDataCallbackStyle();\n<\/pre>\n<p>&nbsp;<\/p>\n<p>Overall, on the plus side we have an event flow that we can follow using indented function calls, but on the negative side this gets out of hand quickly (e.g., callback hell). Here is an animated image of the event flow:<\/p>\n<p>&nbsp;<\/p>\n<p><a href=\"https:\/\/solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/image2.gif\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2682\" src=\"https:\/\/solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/image2.gif\" alt=\"image2\" width=\"600\" height=\"385\" \/><\/a><\/p>\n<p>&nbsp;<\/p>\n<p>If we were to perform the same set of functions but with standard Promises with chaining we might use a function like this (<a href=\"https:\/\/jsfiddle.net\/afrankel\/3rcwb48t\/\" target=\"_blank\" rel=\"noopener\">jsfiddle version<\/a>):<\/p>\n<p>&nbsp;<\/p>\n<pre lang=\"javascript\" line=\"1\">function getAllDataChainingPromises() {\n \/\/ Chaining Promises\n const bank = new SolutionStreetBank()\n let cust, accounts, transactions\n console.log(\"getting customer...\");\n bank.getCustomer(1)\n   .then((response) => {\n     cust = response\n     console.log(\"getting accounts...\");\n     return bank.getAccounts(cust.id)\n   })\n   .then((response) => {\n     accounts = response\n     console.log(\"getting transactions...\");\n     \/\/ to simplify we'll just get transactions based on the first account\n     return bank.getTransactions(accounts[0].id)\n   })\n   .then((response) => {\n     transactions = response\n     console.log('getAllDataCallbackStyle\\n',\n       { cust, accounts, transactions })   \n   })\n}\n\ngetAllDataChainingPromises();\n<\/pre>\n<p>&nbsp;<\/p>\n<p>Overall, on the positive side we have a more structured set of code, but the event flow is somewhat difficult to follow. Here is an animated image of the event flow:<\/p>\n<p>&nbsp;<\/p>\n<p><a href=\"https:\/\/solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/image3.gif\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2684\" src=\"https:\/\/solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/image3.gif\" alt=\"image3\" width=\"600\" height=\"440\" \/><\/a><\/p>\n<p>&nbsp;<\/p>\n<p>If we were to perform the same set of functions using async\/await, we might have a function like this (<a href=\"https:\/\/jsfiddle.net\/afrankel\/8jttnpvx\/\" target=\"_blank\" rel=\"noopener\">jsfiddle version<\/a>):<\/p>\n<p>&nbsp;<\/p>\n<pre lang=\"javascript\" line=\"1\">async function getAllDataAsync() {\n const bank = new SolutionStreetBank()\n console.log(\"getting customer...\");\n const cust = await bank.getCustomer(1)\n console.log(\"getting accounts...\");\n const accounts = await bank.getAccounts(cust.id)\n console.log(\"getting transactions...\");\n \/\/ to simplify we'll just get transactions based on the first account\n const transactions = await bank.getTransactions(accounts[0].id)\n console.log('getAllDataAsync\\n',\n   { cust, accounts, transactions })\n return; \/\/ normally returns a Promise\n}\n\ngetAllDataAsync();\n<\/pre>\n<p>&nbsp;<\/p>\n<p>Now we have a very structured set of code and the event flow is easy to follow. Here is an animated image of the event flow [NOTE: After the first \u201cawait\u201d call it jumps to the end to signify the function returning a Promise.]:<\/p>\n<p>&nbsp;<\/p>\n<p><a href=\"https:\/\/solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/image1.gif\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2679\" src=\"https:\/\/solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/image1.gif\" alt=\"image1\" width=\"600\" height=\"264\" \/><\/a><\/p>\n<p>&nbsp;<\/p>\n<p><strong>Example 3 - Multiple Calls \/ Parallel<\/strong><\/p>\n<p>&nbsp;<\/p>\n<p>Let\u2019s say instead of needing the results of a prior API call, we just want to execute several calls in parallel. We know from Promises we can do this with the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Promise\/all\" target=\"_blank\" rel=\"noopener\">Promise.all<\/a> command and this is no different except we now have the ability to use the \u201cawait\u201d command to simplify things a bit (<a href=\"https:\/\/jsfiddle.net\/afrankel\/ro6q6tra\/\" target=\"_blank\" rel=\"noopener\">jsfiddle version<\/a>):<\/p>\n<p>&nbsp;<\/p>\n<pre lang=\"javascript\" line=\"1\">async function getTransactionsFromDifferentAccountsInParallel() {\n const bank = new SolutionStreetBank()\n console.log(\"getting customer...\");\n const cust = await bank.getCustomer(1)\n console.log(\"getting accounts...\");\n const accounts = await bank.getAccounts(cust.id)\n const transactionsToBeProcessed =\n   accounts.map(account => bank.getTransactions(account.id))\n console.log(\"getting transactions...\");\n const transactions = await Promise.all(transactionsToBeProcessed)\n console.log('getTransactionsFromDifferentAccountsInParallel\\n',\n   JSON.stringify(transactions, null, 2)) \/\/ pretty format\n return; \/\/ normally returns a Promise\n}\n\ngetTransactionsFromDifferentAccountsInParallel();\n<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>Example 4 - For Loops<\/strong><\/p>\n<p>&nbsp;<\/p>\n<p>For me, looping around asynchronous requests was the part that I struggled with the most when using basic callbacks and Promises. I would get lost in my code once I needed to execute a loop or iterator since the control of execution was tougher to follow. With the simplicity of async\/await, which has a more traditional synchronous-looking control of execution, a looping mechanism is much easier to implement and requires no additional thought. <\/p>\n<p>&nbsp; <\/p>\n<p>Similar to our last example where we used a map, here I\u2019m just using a standard \u201cfor loop\u201d to get all of the financial transactions through multiple API calls (<a href=\"https:\/\/jsfiddle.net\/afrankel\/twz49k6z\/\" target=\"_blank\" rel=\"noopener\">jsfiddle version<\/a>):<\/p>\n<p>&nbsp;<\/p>\n<pre lang=\"javascript\" line=\"1\">async function getTransactionsInALoop() {\n const bank = new SolutionStreetBank()\n console.log(\"getting customer...\");\n const cust = await bank.getCustomer(1)\n console.log(\"getting accounts...\");\n const accounts = await bank.getAccounts(cust.id)\n console.log(\"getting transactions...\");\n let transactions = [];\n for(let i=0; i<accounts.length; i++) {\n   let transactionsForAccount =\n     await bank.getTransactions(accounts[i].id)\n   transactions.push(transactionsForAccount)\n }\n console.log('getTransactionsInALoop\\n',\n   JSON.stringify(transactions, null, 2)) \/\/ pretty format\n return; \/\/ normally returns a Promise\n}\n\ngetTransactionsInALoop();\n<\/pre>\n<p>&nbsp;<\/p>\n<p>Of course, besides \u201cfor loops\u201d and other iterators, \u201cif\u201d conditions are routine as well.<\/p>\n<p>&nbsp;<\/p>\n<p><strong>Example 5 - Error Handling<\/strong><\/p>\n<p>&nbsp;<\/p>\n<p>Again, because we are operating in a typical synchronous-looking pattern, error handling (as in user validation errors) is handled as it would normally be handled in any code.<\/p>\n<p>&nbsp;<\/p>\n<p><strong>Example 6 - Exception Handling<\/strong><\/p>\n<p>&nbsp;<\/p>\n<p>Since async\/await uses the good old <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Guide\/Control_flow_and_error_handling#try...catch_statement\" target=\"_blank\" rel=\"noopener\">try\/catch blocks<\/a>, many of you who are familiar with typed languages would be familiar with this type of exception handling. In general, any errors in the catch block are unexpected (as compared to basic validation\/error handling) and should be handled in the appropriate way based on the await calls being made. Never should the catch block just console.log the error or do nothing. All exceptions should be raised and handled.  <a href=\"https:\/\/scotch.io\/tutorials\/proper-error-handling-in-javascript\" target=\"_blank\" rel=\"noopener\">Here is a good article<\/a> on the subject for further reading.<\/p>\n<p>&nbsp;<\/p>\n<p><strong>Summary<\/strong><\/p>\n<p>&nbsp;<\/p>\n<p>JavaScript and some of its syntax and implementation are often a bit hard to understand especially around asynchronous calling, but I believe with async\/await the JavaScript language IS getting better. With these improvements, the adoption level of using JavaScript on the server should increase in the next few years and its use on the client will continue to be strong.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>&nbsp; The famous line from a Beatles song also pertains to the JavaScript language. The JavaScript of years gone past in the late 90s has certainly come a long way from its early adoption. No one could have foreseen its rise to power and usage. &nbsp; JavaScript seems to be everywhere nowadays including on the [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-2665","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.3 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>It&#039;s Getting Better All The Time - Making the Complex Simple Using Async\/Await in JavaScript - Solution Street Blog<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.solutionstreet.com\/blog\/2018\/03\/28\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"It&#039;s Getting Better All The Time - Making the Complex Simple Using Async\/Await in JavaScript - Solution Street Blog\" \/>\n<meta property=\"og:description\" content=\"&nbsp; The famous line from a Beatles song also pertains to the JavaScript language. The JavaScript of years gone past in the late 90s has certainly come a long way from its early adoption. No one could have foreseen its rise to power and usage. &nbsp; JavaScript seems to be everywhere nowadays including on the [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.solutionstreet.com\/blog\/2018\/03\/28\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\/\" \/>\n<meta property=\"og:site_name\" content=\"Solution Street Blog\" \/>\n<meta property=\"article:published_time\" content=\"2018-03-28T15:01:12+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/guitarguytitle2-300x187.png\" \/>\n<meta name=\"author\" content=\"Peggy Frankel\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Peggy Frankel\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"10 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/2018\\\/03\\\/28\\\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/2018\\\/03\\\/28\\\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\\\/\"},\"author\":{\"name\":\"Peggy Frankel\",\"@id\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/#\\\/schema\\\/person\\\/c4846451eff30e9514b534b2a2e01696\"},\"headline\":\"It&#8217;s Getting Better All The Time &#8211; Making the Complex Simple Using Async\\\/Await in JavaScript\",\"datePublished\":\"2018-03-28T15:01:12+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/2018\\\/03\\\/28\\\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\\\/\"},\"wordCount\":1890,\"commentCount\":0,\"image\":{\"@id\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/2018\\\/03\\\/28\\\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/solutionstreet.com\\\/blog\\\/wp-content\\\/uploads\\\/2018\\\/03\\\/guitarguytitle2-300x187.png\",\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/2018\\\/03\\\/28\\\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/2018\\\/03\\\/28\\\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\\\/\",\"url\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/2018\\\/03\\\/28\\\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\\\/\",\"name\":\"It's Getting Better All The Time - Making the Complex Simple Using Async\\\/Await in JavaScript - Solution Street Blog\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/2018\\\/03\\\/28\\\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/2018\\\/03\\\/28\\\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/solutionstreet.com\\\/blog\\\/wp-content\\\/uploads\\\/2018\\\/03\\\/guitarguytitle2-300x187.png\",\"datePublished\":\"2018-03-28T15:01:12+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/#\\\/schema\\\/person\\\/c4846451eff30e9514b534b2a2e01696\"},\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/2018\\\/03\\\/28\\\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/2018\\\/03\\\/28\\\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/2018\\\/03\\\/28\\\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\\\/#primaryimage\",\"url\":\"https:\\\/\\\/solutionstreet.com\\\/blog\\\/wp-content\\\/uploads\\\/2018\\\/03\\\/guitarguytitle2-300x187.png\",\"contentUrl\":\"https:\\\/\\\/solutionstreet.com\\\/blog\\\/wp-content\\\/uploads\\\/2018\\\/03\\\/guitarguytitle2-300x187.png\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/2018\\\/03\\\/28\\\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"It&#8217;s Getting Better All The Time &#8211; Making the Complex Simple Using Async\\\/Await in JavaScript\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/\",\"name\":\"Solution Street Blog\",\"description\":\"Quality Software Engineering - Technology and Consulting Articles\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/#\\\/schema\\\/person\\\/c4846451eff30e9514b534b2a2e01696\",\"name\":\"Peggy Frankel\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/af71ceb16f89d32c9bb825a47f8057da9283b4a27a934bf0c47cdef65ad0eb5d?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/af71ceb16f89d32c9bb825a47f8057da9283b4a27a934bf0c47cdef65ad0eb5d?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/af71ceb16f89d32c9bb825a47f8057da9283b4a27a934bf0c47cdef65ad0eb5d?s=96&d=mm&r=g\",\"caption\":\"Peggy Frankel\"},\"url\":\"https:\\\/\\\/www.solutionstreet.com\\\/blog\\\/author\\\/pfrankel\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"It's Getting Better All The Time - Making the Complex Simple Using Async\/Await in JavaScript - Solution Street Blog","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.solutionstreet.com\/blog\/2018\/03\/28\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\/","og_locale":"en_US","og_type":"article","og_title":"It's Getting Better All The Time - Making the Complex Simple Using Async\/Await in JavaScript - Solution Street Blog","og_description":"&nbsp; The famous line from a Beatles song also pertains to the JavaScript language. The JavaScript of years gone past in the late 90s has certainly come a long way from its early adoption. No one could have foreseen its rise to power and usage. &nbsp; JavaScript seems to be everywhere nowadays including on the [&hellip;]","og_url":"https:\/\/www.solutionstreet.com\/blog\/2018\/03\/28\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\/","og_site_name":"Solution Street Blog","article_published_time":"2018-03-28T15:01:12+00:00","og_image":[{"url":"https:\/\/solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/guitarguytitle2-300x187.png","type":"","width":"","height":""}],"author":"Peggy Frankel","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Peggy Frankel","Est. reading time":"10 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.solutionstreet.com\/blog\/2018\/03\/28\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\/#article","isPartOf":{"@id":"https:\/\/www.solutionstreet.com\/blog\/2018\/03\/28\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\/"},"author":{"name":"Peggy Frankel","@id":"https:\/\/www.solutionstreet.com\/blog\/#\/schema\/person\/c4846451eff30e9514b534b2a2e01696"},"headline":"It&#8217;s Getting Better All The Time &#8211; Making the Complex Simple Using Async\/Await in JavaScript","datePublished":"2018-03-28T15:01:12+00:00","mainEntityOfPage":{"@id":"https:\/\/www.solutionstreet.com\/blog\/2018\/03\/28\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\/"},"wordCount":1890,"commentCount":0,"image":{"@id":"https:\/\/www.solutionstreet.com\/blog\/2018\/03\/28\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\/#primaryimage"},"thumbnailUrl":"https:\/\/solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/guitarguytitle2-300x187.png","inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.solutionstreet.com\/blog\/2018\/03\/28\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.solutionstreet.com\/blog\/2018\/03\/28\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\/","url":"https:\/\/www.solutionstreet.com\/blog\/2018\/03\/28\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\/","name":"It's Getting Better All The Time - Making the Complex Simple Using Async\/Await in JavaScript - Solution Street Blog","isPartOf":{"@id":"https:\/\/www.solutionstreet.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.solutionstreet.com\/blog\/2018\/03\/28\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\/#primaryimage"},"image":{"@id":"https:\/\/www.solutionstreet.com\/blog\/2018\/03\/28\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\/#primaryimage"},"thumbnailUrl":"https:\/\/solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/guitarguytitle2-300x187.png","datePublished":"2018-03-28T15:01:12+00:00","author":{"@id":"https:\/\/www.solutionstreet.com\/blog\/#\/schema\/person\/c4846451eff30e9514b534b2a2e01696"},"breadcrumb":{"@id":"https:\/\/www.solutionstreet.com\/blog\/2018\/03\/28\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.solutionstreet.com\/blog\/2018\/03\/28\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.solutionstreet.com\/blog\/2018\/03\/28\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\/#primaryimage","url":"https:\/\/solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/guitarguytitle2-300x187.png","contentUrl":"https:\/\/solutionstreet.com\/blog\/wp-content\/uploads\/2018\/03\/guitarguytitle2-300x187.png"},{"@type":"BreadcrumbList","@id":"https:\/\/www.solutionstreet.com\/blog\/2018\/03\/28\/its-getting-better-all-the-time-making-the-complex-simple-using-asyncawait-in-javascript\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.solutionstreet.com\/blog\/"},{"@type":"ListItem","position":2,"name":"It&#8217;s Getting Better All The Time &#8211; Making the Complex Simple Using Async\/Await in JavaScript"}]},{"@type":"WebSite","@id":"https:\/\/www.solutionstreet.com\/blog\/#website","url":"https:\/\/www.solutionstreet.com\/blog\/","name":"Solution Street Blog","description":"Quality Software Engineering - Technology and Consulting Articles","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.solutionstreet.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.solutionstreet.com\/blog\/#\/schema\/person\/c4846451eff30e9514b534b2a2e01696","name":"Peggy Frankel","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/af71ceb16f89d32c9bb825a47f8057da9283b4a27a934bf0c47cdef65ad0eb5d?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/af71ceb16f89d32c9bb825a47f8057da9283b4a27a934bf0c47cdef65ad0eb5d?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/af71ceb16f89d32c9bb825a47f8057da9283b4a27a934bf0c47cdef65ad0eb5d?s=96&d=mm&r=g","caption":"Peggy Frankel"},"url":"https:\/\/www.solutionstreet.com\/blog\/author\/pfrankel\/"}]}},"_links":{"self":[{"href":"https:\/\/www.solutionstreet.com\/blog\/wp-json\/wp\/v2\/posts\/2665","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.solutionstreet.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.solutionstreet.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.solutionstreet.com\/blog\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/www.solutionstreet.com\/blog\/wp-json\/wp\/v2\/comments?post=2665"}],"version-history":[{"count":0,"href":"https:\/\/www.solutionstreet.com\/blog\/wp-json\/wp\/v2\/posts\/2665\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.solutionstreet.com\/blog\/wp-json\/wp\/v2\/media?parent=2665"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.solutionstreet.com\/blog\/wp-json\/wp\/v2\/categories?post=2665"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.solutionstreet.com\/blog\/wp-json\/wp\/v2\/tags?post=2665"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}