I am trying to call a function and wait till the function gets data before further statements get executed. I am new to node js and async/await and promises. I tried some solutions but doesn't work it always returning Promise { undefined }.
If I run code without using a separate function it works fine. but I have to use functions here for database connection.
here's my code.
db.js
const mongoClient = require('mongodb').MongoClient;
const db_url = "mongodb_url";
const database_name = "mydb";
module.exports.GetAllUsersData = async function (){
mongoClient.connect(db_url,{ useUnifiedTopology: true },function(err,dbserver){
if(err) throw err;
var mydb = dbserver.db(database_name);
mydb.collection('users').find({}).toArray(function(err,results){
console.log(results); //I am getting data here
return Promise.resolve(results);
});
});
}
app.js
const express = require('express');
const db = require('./db.js');
//
const app = express();
app.set(express.static('public'));
app.set('view engine','ejs');
var urlencodeparser = express.urlencoded({extended:false});
app.get('/',function(req,res){
var results = db.GetAllUsersData();
results.then(console.log(results)); //getting promise {undefined} here
res.render('home.ejs',{users:results})
})
console.log('connected...')
app.listen(9000);