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');
}
})
});
}
Related Article: How to use async-await in node js
BY Best Interview Question ON 17 Jun 2020