The Wayback Machine - https://web.archive.org/web/20220707033117/https://www.geeksforgeeks.org/explain-async-await-with-promises-in-node-js/
Skip to content
Related Articles

Related Articles

Explain Async Await with promises in Node.js

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 25 May, 2022

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
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!