0

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);
Vahida Vadiya
  • 144
  • 1
  • 12
  • Are you sure you want to be connecting before a single query? Why not connect once at the start of the process? Anyway, you're only returning the promise you resolve to the enclosing scope in `connect` which is ignored. It's not a good idea to combine callback and promise patterns like this. – ggorlen Jul 06 '21 at 01:51
  • would you please suggest how can I use it – Vahida Vadiya Jul 06 '21 at 01:57
  • I suggest connecting to your database at the start of the process unless you have a good reason not to. If you do this, the nested callback/promise problem here becomes a non-issue. – ggorlen Jul 06 '21 at 01:59
  • thanks I will try to do that way.. do you have any comment on promise {undefined}. I am not able to get data in my app.js – Vahida Vadiya Jul 06 '21 at 02:01
  • 2
    Yes, your function is `async` which always returns a promise, and when control reaches the end of the function it automatically returns undefined, hence your result. I understand you aren't able to get data, and I explained why: `return Promise.resolve(results)` doesn't send the data anywhere useful. You could wrap the whole thing in `return new Promise((resolve, reject) => /* your whole function body */ );` and call `resolve(results)`, but this is a [pretty awful place to be](https://stackoverflow.com/questions/23803743). – ggorlen Jul 06 '21 at 02:02
  • how should I return data from the function.. sorry I am a newbie – Vahida Vadiya Jul 06 '21 at 02:06
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – ggorlen Jul 06 '21 at 02:07

1 Answers1

1

You can make it work by rewriting your GetAllUserData function as follows:

module.exports.GetAllUsersData = function () {
    return new Promise((resolve, reject) => {
        mongoClient.connect(db_url,{ useUnifiedTopology: true },function(err,dbserver){
            if(err) reject(err);
            var mydb = dbserver.db(database_name);
            mydb.collection('users').find({}).toArray(function(err,results){
                console.log(results); //I am getting data here
                resolve(results);                
            });
        });
    });
});