1.

How to use Async Await with promises in node js?

Answer»
  • 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');
                 }
          })
    });
    }
Related Article: How to use async-await in node js


Discussion

No Comment Found