Loading…

How to use Async Await with promises in node js?

  • Step1. Install Async first with "npm install async" command
  • Step2. Call the async in your file with you will use async.
    var async = require("async");
  • Step3. Make an async function and call await function inside async function.
    let phoneChecker = async function (req, res) {
         const result = await phoneExistOrNot();
    }
    exports.phoneChecker = phoneChecker;

    await will work only under async function.

    For example: here is " phoneChecker " is async function, and phoneExistOrNot is await service.
  • Step4. Now you can write your logic in await function.
    let phoneExistOrNot = async function (req, res){
        return new Promise(function(resolve, reject) {
            db.query('select name, phone from users where phone = 123456789 ', function (error, result) {
                 if(error) {
                     reject(error);
                     console.log('Error');
                 } else {
                      resolve(result);
                      console.log('Success');
                 }
          })
    });
    }

We have a separate blog for this topic. You can also read this concept in details
How to use async-await in node js

Suggest An Answer

No suggestions avaliable!

Latest post from Node js Interview Questions

Ask Question