Tutorial - Using Async Await in Node.js

Tutorial - Using Async Await in Node.js

Before Node version 7.6, the callbacks were the only official way provided by Node to run one function after another. As Node architecture is single-threaded and asynchronous, the community devised the callback functions, which would fire (or run) after the first function (to which the callbacks were assigned) run is completed.

Example of a Callback:

app.get('/', function(){
 function1(arg1, function(){

The problem with this kind of code is that this kind of situations can cause a lot of trouble and the code can get messy when there are several functions. This situation is called what is commonly known as a callback hell.

So, to find a way out, the idea of Promises and function chaining was introduced.

Example: Before async/await

function fun1(req, res){
  return request.get('http://localhost:3000')
   .catch((err) =>{
     console.log('found error');
}).then((res) =>{
   console.log('get request returned.');


The above code demos a function implemented with function chaining instead of callbacks. It can be observed that the code is now more easy to understand and readable. The code basically says that GET localhost:3000, catch the error if there is any; if there is no error then implement the following statement:

console.log(‘get request returned.’);


Example: After async/await

async function fun1(req, res){
  let response = await request.get('http://localhost:3000');
    if (response.err) { console.log('error');}
    else { console.log('fetched response');


The code above basically asks the javascript engine running the code to wait for the request.get() function to complete before moving on to the next line to execute it. The request.get() function returns a Promise for which user will await . Before async/await, if it needs to be made sure that the functions are running in the desired sequence, that is one after the another, chain them one after the another or register callbacks.

Code writing and understanding becomes easy with async/await as can be observed from both the examples.

Originally published by Parikshit Hooda at  geeksforgeeks.org



How To Master Async/Await With This Real World Example

JavaScript — from callbacks to async/await

Write beautiful Node.js APIs using async/await and Firebase

JavaScript Tutorial for Async / Await with Angular 7/8 Observation example and HTTP


Learn Startup - Build a successful business and change the world


Most Popular JavaScript Frameworks 2019 - I'm Programmer

Building a Video Blog with Gatsby and Markdown (MDX)

How to check if Checkbox is Checked or not using Plain JavaScript

10 Node Frameworks to Use in 2019