Open In App

Explain Async Await with promises in Node.js

Improve
Improve
Like Article
Like
Save
Share
Report

Modern javascript brings with it the async-await feature which enables developers to write asynchronous code in a way that looks and feels synchronous. This helps to remove many of the problems with nesting that promises have, and as a bonus can make asynchronous code much easier to read and write. 

To use async-await, we just need to create an async function in which we will implement our try-catch block. In the try block, we will await our promise to be completed. If it gets resolved we will get the result otherwise an error will be thrown through the catch block. Await can only be used inside an async function or async callback or async arrow function.

Example:

Javascript




const mod = (a, b) => {
    return new Promise((resolve, reject) => {
        if (b == 0) {
            // Rejected (error)
            reject("Modulo zero is not allowed");
        } else {
            // Resolved (Success)
            resolve(a % b);
        }
    });
};
  
// 5 mod 2 will give result 1
async function _5mod2() {
    try {
        const res = await mod(5, 2);
        console.log(`The result of division is ${res}`);
    } catch (err) {
        console.log(err);
    }
};
_5mod2();
  
// 5 mod 0 will give error
async function _5mod0() {
    try {
        const res = await mod(5, 0);
        console.log(`The result of division is ${res}`);
    } catch (err) {
        console.log(err);
    }
};
_5mod0();


Output:

The result of division is 1
Modulo zero is not allowed

Last Updated : 25 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads