Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

How to use async-await in node js with example

In this chapter, you will learn how to use async and await in node js with example.

How to use async await in node js with example

  1. Async and await keywords are the major improvements in the javascript to work with promises and
  2. They are not same as call back or promises.
  3. Async and await keywords are a small set of methods that help to work with asynchronous code like promises.

Let’s see the below snippet output

const employeeFullName = () => {

}
console.log(employeeFullName());
// output
// undefined

As we can see in the above example when we call the arrow function employeeFullName, it returns undefined. Its not only the arrow function that defines undefined, but even a normal function in javascript also returns the undefined, let’s take a look on below code snippet. If you are not returning anything from the function, javascript function will return undefined implicitly.

function employeeDepartment() {

}
console.log(employeeDepartment());

// output
// undefined

How to define an async function?

  1. An async function can be defined with the keyword async.
  2. Async functions always return a promise.
  3. The returned value can be defined by the programmer.

Now let’s take a look on below code snippet.

const employeeFullName = async () => {

}
console.log(employeeFullName());

// output
// Promise { undefined }

Now return some value from the Async function. Let’s see the below snippet

const employeeFullName = async () => {
    return 'Learn simpli';
}
console.log(employeeFullName());

Promise { 'Learn simpli' }

Now we can use the chaining method with the async function. let’s see the below code snippet that returns employee full details. After calling the promises everything we see in the result is an empty object.

// Promise that returns employee full name
    const employeeFullName = (firstName, lastName) => {
        return new Promise((resolve, reject) => {
            resolve('Employee full name is :' + firstName + ' ' + lastName);
        })
    };

    // Promise that returns employee department
    const employeeDepartment = (department) => {
        return new Promise((resolve, reject) => {
            resolve('Employee department name is :' + department);
        })
    };

    // Promise that returns employee 
    const employeeSalary = (salary) => {
        return new Promise((resolve, reject) => {
            resolve('Employee salary is :' + salary);
        })
    };

    const getEmployeeDetails = async () => {
         
        let fullName =  employeeFullName('John', 'Mickel');
        let department = employeeDepartment('Software development');
        let salary = employeeSalary(5000);
        return fullName+'\n'+department+'\n'+salary;
    }

    getEmployeeDetails().then((result) => {
        console.log(result);
    }).catch((e) =>{
        console.log(e);
    });

    // output 
    // [object Promise]
    // [object Promise]
    // [object Promise]

Disadvantages of promise chaining:

  1. Every individual promise that returns the result has a different scope
  2. No ability to access all the individual result at the same time

How to use await with async function?
To solve the complexity that happens with promise chaining we can use async and await methods. As we can see in the above code snippet, everything we are seeing in the result is an empty object. Well, that’s because if we call any promises in the async function it won’t wait for the result, instead, it executes the next line. Await keyword will help us to solve this. Await keyword waits for still the response is returned from the promise and then it executes the next line. Let’s take a look at how a to await keyword can be used inside the async function.

// Promise that returns employee full name
    const employeeFullName = (firstName, lastName) => {
        return new Promise((resolve, reject) => {
            resolve('Employee full name is :' + firstName + ' ' + lastName);
        })
    };

    // Promise that returns employee department
    const employeeDepartment = (department) => {
        return new Promise((resolve, reject) => {
            resolve('Employee department name is :' + department);
        })
    };

    // Promise that returns employee 
    const employeeSalary = (salary) => {
        return new Promise((resolve, reject) => {
            resolve('Employee salary is :' + salary);
        })
    };

    const getEmployeeDetails = async () => {
         
        let fullName = await employeeFullName('John', 'Mickel');
        let department = await employeeDepartment('Software development');
        let salary = await employeeSalary(5000);
        return fullName+'\n'+department+'\n'+salary;
    }

    getEmployeeDetails().then((result) => {
        console.log(result);
    }).catch((e) =>{
        console.log(e);
    });

    // output 
    // Employee full name is :John Mickel
    // Employee department name is :Software development
    // Employee salary is :5000

 

One thought on “How to use async await in node js with example

Comments are closed.