sad puppy waiting Async and Await are extensions of promises. So if you are not clear about the basics of promises please get comfortable with promises before reading further. You can read my post on Understanding Promises in Javascript. If you would like to highlights some parts of this article you can use our extension . You can search for your previous highlights from the dashboard on http://bit.ly/highlights-extension https://alpha.app.learningpaths.io/#/highlights I am sure that many of you would be using async and await already. But I think it deserves a little more attention. Here is a small test : If you can’t spot the problem with the below code then read on. for (name of ["nkgokul", "BrendanEich", "gaearon"]) {userDetails = await fetch(" " + name);userDetailsJSON = await userDetails.json();console.log("userDetailsJSON", userDetailsJSON);} https://api.github.com/users/ We will revisit the above code block later, once we have gone through async await basics. Like always is your friend. Especially checkout the definitions. Mozilla docs async and await From MDN An asynchronous function is a function which operates asynchronously via the event loop, using an implicit to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions. [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.") I wonder who writes these descriptions. They are so concise and well articulated. To break it down. The function operates asynchronously via event loop. It uses an implicit Promise to return the result. The syntax and structure of the code is similar to writing synchronous functions. And MDN goes on to say An function can contain an expression that pauses the execution of the async function and waits for the passed 's resolution, and then resumes the function's execution and returns the resolved value. Remember, the keyword is only valid inside functions. async [await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await "The await operator is used to wait for a Promise. It can only be used inside an async function.") Promise async await async Let us jump into code to understand this better. We will reuse the three function we used for understanding promises here as well. A function that returns a promise which resolves or rejects after n number of seconds. var promiseTRRARNOSG = ( = function() {return new Promise(function(resolve, reject) {let randomNumberOfSeconds = getRandomNumber(2, 10);setTimeout(function() {let randomiseResolving = getRandomNumber(1, 10);if (randomiseResolving > 5) {resolve({randomNumberOfSeconds: randomNumberOfSeconds,randomiseResolving: randomiseResolving});} else {reject({randomNumberOfSeconds: randomNumberOfSeconds,randomiseResolving: randomiseResolving});}}, randomNumberOfSeconds * 1000);});}); promiseThatResolvesRandomlyAfterRandomNumnberOfSecondsGenerator Two more deterministic functions one which resolve after n seconds and another which rejects after n seconds. var promiseTRSANSG = (promiseThatResolvesAfterNSecondsGenerator = function(n = 0) {return new Promise(function(resolve, reject) {setTimeout(function() {resolve({resolvedAfterNSeconds: n});}, n * 1000);});});var promiseTRJANSG = (promiseThatRejectsAfterNSecondsGenerator = function(n = 0) {return new Promise(function(resolve, reject) {setTimeout(function() {reject({rejectedAfterNSeconds: n});}, n * 1000);});}); Since all these three functions are returning promises we can also call these functions as asynchronous functions. See we wrote asyn functions even before knowing about them. If we had to use the function using standard format of promises we would have written something like this. promiseTRSANSG var promise1 = promiseTRSANSG(3);promise1.then(function(result) {console.log(result);}); promise1.catch(function(reason) {console.log(reason);}); There is a lot of unnecessary code here like anonymous function just for assigning the handlers. What async await does is it improves the syntax for this which would make seem more like synchronous code. If we had to the same as above in async await format it would be like result = await promiseTRSANSG(3);console.log(result); Well that look much more readable than the standard promise syntax. When we used the execution of the code was blocked. That is the reason that you had the value of the promise resolution in the variable . As you can make out from the above code sample, instead of the part the result is assigned to the variable directly when you use You can also make out that the part is not present here. That is because that is handled using error handling. So instead of using let us use Since this function can either resolve or reject we need to handle both the scenarios. In the above code we just wrote two lines to give you an easy comparison between the standard format and format. The example in next section gives you a better idea of the format and structure. await result .then await .catch try catch promiseTRSANS promiseTRRARNOSG async await General syntax of using async await async function testAsync() {for (var i = 0; i < 5; i++) {try {result1 = await promiseTRRARNOSG();console.log("Result 1 ", result1);result2 = await promiseTRRARNOSG();console.log("Result 2 ", result2);} catch (e) {console.log("Error", e);} finally {console.log("This is done");}}} testAsync(); From the above code example you can make out that instead of using the promise specific error handling we are using the more generic approach of using for error handling. So that is one thing less for us to remember and it also improves the overall readability even after considering the try catch block around our code. So based on the level of error handling you need you can add any number of blocks and make the error messages more specific and meaningful. try catch catch Pitfalls of using async and await makes it much more easier to use promises. Developers from synchronous programming background will feel at home while using and . This should also alert us, as this also means that we are moving towards a more synchronous approach if we don’t keep a watch. async await async await The whole point of javascript/nodejs is to think asynchronous by default and not an after though. generally means you are doing things in sequential way. So make a conscious decision whenever you want to use to async await. async await Now let us start analysing the code that I flashed at your face in the beginning. for (name of ["nkgokul", "BrendanEich", "gaearon"]) {userDetails = await fetch(" " + name);userDetailsJSON = await userDetails.json();console.log("userDetailsJSON", userDetailsJSON);} https://api.github.com/users/ This seems like a harmless piece of code that fetches the github details of three users Right. That is true. That is what this function does. But it also has some unintended consequences. “nkgokul”, “BrendanEich”, “gaearon” Before diving further into the code let us build a simple timer. startTime = performance.now(); //Run at the beginning of the code function executingAt() {return (performance.now() - startTime) / 1000;} Now we can use wherever we want to print the number of seconds that have surpassed since the beginning. executingAt async function fetchUserDetailsWithStats() {i = 0;for (name of ["nkgokul", "BrendanEich", "gaearon"]) {i++;console.log("Starting API call " + i + " at " + executingAt());userDetails = await fetch(" " + name);userDetailsJSON = await userDetails.json();console.log("Finished API call " + i + "at " + executingAt());console.log("userDetailsJSON", userDetailsJSON);}} https://api.github.com/users/ Checkout the output of the same. async-await analysed As you can find from the output, each of the await function is called after the previous function was completed. We are trying to fetch the details of three different users It is pretty obvious that output of one API call is in noway dependent on the output of the others. “nkgokul”, “BrendanEich”, “gaearon” The only dependence we have is these two lines of code. userDetails = await fetch(" " + name);userDetailsJSON = await userDetails.json(); https://api.github.com/users/ We can create the object only after getting the . Hence it makes sense to use await here that is within the scope of getting the details of a single user. So let us make an for getting the details of the single user. userDetailsJSON userDetails async async function fetchSingleUsersDetailsWithStats(name) {console.log("Starting API call for " + name + " at " + executingAt());userDetails = await fetch(" " + name);userDetailsJSON = await userDetails.json();console.log("Finished API call for " + name + " at " + executingAt());return userDetailsJSON;} https://api.github.com/users/ Now that the is async we can use this function to fetch the details of the different users in parallel. fetchSingleUsersDetailsWithStats async function fetchAllUsersDetailsParallelyWithStats() {let singleUsersDetailsPromises = [];for (name of ["nkgokul", "BrendanEich", "gaearon"]) {let promise = fetchSingleUsersDetailsWithStats(name);console.log("Created Promise for API call of " + name + " at " + executingAt());singleUsersDetailsPromises.push(promise);}console.log("Finished adding all promises at " + executingAt());let allUsersDetails = await Promise.all(singleUsersDetailsPromises);console.log("Got the results for all promises at " + executingAt());console.log(allUsersDetails);} When you want to run things in parallel, the thumb rule that I follow is Create a promise for each async call. Add all the promises to an array. Then pass the promises array to Promise.all This in turn returns a single promise for which we can use await When we put all of this together we get startTime = performance.now();async function fetchAllUsersDetailsParallelyWithStats() {let singleUsersDetailsPromises = [];for (name of ["nkgokul", "BrendanEich", "gaearon"]) {let promise = fetchSingleUsersDetailsWithStats(name);console.log("Created Promise for API call of " + name + " at " + executingAt());singleUsersDetailsPromises.push(promise);}console.log("Finished adding all promises at " + executingAt());let allUsersDetails = await Promise.all(singleUsersDetailsPromises);console.log("Got the results for all promises at " + executingAt());console.log(allUsersDetails);} async function fetchSingleUsersDetailsWithStats(name) {console.log("Starting API call for " + name + " at " + executingAt());userDetails = await fetch(" " + name);userDetailsJSON = await userDetails.json();console.log("Finished API call for " + name + " at " + executingAt());return userDetailsJSON;}fetchAllUsersDetailsParallelyWithStats(); https://api.github.com/users/ The output for this is Promises run in parallel with timestamps As you can make out from the output, promise creations are almost instantaneous whereas API calls take some time. We need to stress this as time taken for promises creation and processing is trivial when compared to IO operations. So while choosing a promise library it makes more sense to choose a library that is feature rich and has better dev experience. Since we are using all the API calls were run in parallel. Each API is taking almost 0.88 seconds. But since they are called in parallel we were able to get the results of all API calls in 0.89 seconds. Promise.all In most of the scenarios understanding this much should serve us well. You can skip to Thumb Rules section. But if you want to dig deeper read on. Digging deeper into await For this let us pretty much limit ourselves to function. The outcome of this function is more deterministic and will help us identify the differences. promiseTRSANSG Sequential Execution startTime = performance.now();var sequential = async function() {console.log(executingAt());const resolveAfter3seconds = await promiseTRSANSG(3);console.log("resolveAfter3seconds", resolveAfter3seconds);console.log(executingAt());const resolveAfter4seconds = await promiseTRSANSG(4);console.log("resolveAfter4seconds", resolveAfter4seconds);end = executingAt();console.log(end);}sequential(); Sequential Execution Parallel Execution using Promise.all var parallel = async function() {startTime = performance.now();promisesArray = [];console.log(executingAt());promisesArray.push(promiseTRSANSG(3));promisesArray.push(promiseTRSANSG(4));result = await Promise.all(promisesArray);console.log(result);console.log(executingAt());}parallel(); Parallel execution using promises Concurrent Start of Execution asynchronous execution starts as soon as the is created. just blocks the code within the function until the promise is resolved. Let us create a function which will help us clearly understand this. promise await async var concurrent = async function() {startTime = performance.now();const resolveAfter3seconds = promiseTRSANSG(3);console.log("Promise for resolveAfter3seconds created at ", executingAt());const resolveAfter4seconds = promiseTRSANSG(4);console.log("Promise for resolveAfter4seconds created at ", executingAt()); resolveAfter3seconds.then(function(){console.log("resolveAfter3seconds resolved at ", executingAt());}); resolveAfter4seconds.then(function(){console.log("resolveAfter4seconds resolved at ", executingAt());}); console.log(await resolveAfter4seconds);console.log("await resolveAfter4seconds executed at ", executingAt());console.log(await resolveAfter3seconds);console.log("await resolveAfter3seconds executed at ", executingAt()); };concurrent(); Concurrent start and then await From previous post we know that is even driven. That is is executed as soon as the promise is resolved. So let us use and to identify when our promises are actually resolved. From the output we can see that is resolved after 3 seconds and is executed after 4 seconds. This is as expected. .then .then resolveAfter3seconds.then resolveAfter4seconds.then resolveAfter3seconds resolveAfter4seconds Now to check how affects the execution of code we have used await console.log(await resolveAfter4seconds);console.log(await resolveAfter3seconds); As we have seen from the output of resolved one second before . But we have the for and then followed by for .then resolveAfter3seconds resolveAfter4seconds await resolveAfter4seconds await resolveAfter3seconds From the output we can see that though was already resolved it got printed only after the output of was printed. Which reiterates what we had said earlier. only blocks the execution of next lines of code in function and doesn’t affect the promise execution. resolveAfter3seconds console.log(await resolveAfter4seconds); await async Disclaimer mentions that is still serial and using is truly parallel. I have not been able to understand the difference and would love to hear back if anybody has figured out their heard around the difference. MDN documentation Promise.all .then Thumb Rules Here are a list of thumb rules I use to keep my head sane around using and async await functions returns a promise. async functions use an implicit Promise to return its result. Even if you don’t return a promise explicitly function makes sure that your code is passed through a promise. async async blocks the code execution within the function, of which it( ) is a part. await async await statement There can be multiple statements within a single function. await async When using make sure to use for error handling. async await try catch If your code contains blocking code it is better to make it an function. By doing this you are making sure that somebody else can use your function asynchronously. async By making async functions out of blocking code, you are enabling the user who will call your function to decide on the level of asynhronicity he wants. Be extra careful when using within loops and iterators. You might fall into the trap of writing sequentially executing code when it could have been easily done in parallel. await is always for a single promise. If you want to multiple promises(Run this promises in parallel) create an array of promises and then pass it to the function. await await Promise.all Promise creation starts the execution of asynchronous functionality. only blocks the code execution within the function. It only makes sure that next line is executed when the resolves. So if an asynchronous activity has already started then will not have an effect on it. await async promise await Please point out if I am missing something here or if something can be improved. If you didn’t have anything new to learn from this post and you are from Bangalore then we would like to hire you. We have a opening in our product team. Leave a private message if you would like to know further. If you liked this article and would like to read similar articles, don’t forget to clap. Click and drag to clap more than once. 50 is the limit. Understanding Series This article is a part of my learning series, which I call . You can read more above it Understanding X in this link. Understanding Javascript _I have had a kind of “love and hate” relationship with JavaScript. But nevertheless JavaScript was always intriguing…_hackernoon.com Understanding promises in JavaScript _Async and Await are extensions of promises. So if you are not clear about the basics of promises please get comfortable…_hackernoon.com Understanding async-await in Javascript _I recently read a medium post where the author claimed that using async-await is better than using promises. While this…_hackernoon.com Should I use Promises or Async-Await _I think npm was one of the reasons for quick adoption of nodejs. As of writing this article there are close 7,00,000…_hackernoon.com Understanding npm in Nodejs Understanding Linux _Survival guide for those who are starting with Linux_hackernoon.com Linux Survival Guide for Beginners _Monitor all your server infrastructure_hackernoon.com Understanding Zabbix _Ubuntu Firewall for humans_hackernoon.com Understanding UFW _Monitoring services and starting them on boot_hackernoon.com Linux Systemctl Understanding React _React is all about keeping your front-end code modular and reusable. Components play a crucial role in making React…_hackernoon.com Understanding Functional Components Understanding Learning _The dictionary meaning of a rabbit hole is as follows._medium.com The Thing about Rabbit Holes Understanding Cryptocurrencies _Price is an important indicator. But it can also be misleading in many cases._blog.goodaudience.com Why comparing cryptocurrency prices is wrong _It has been more than an year since I started investing in cryptocurrencies. Following Warren Buffet’s advice of “Never…_hackernoon.com Beginner’s Guide to “Investing in Cryptocurrencies”