Matrix
Matrix

Reputation: 21

res.send() is running before nested function completes with value

The 'GetUsers' function is running and it returns the correct values as expected. However, res.send(users) is running before the nested function has completed with the value so it is undefined. I have tried doing the res.send(users) from inside the nested function but it doesn't recognize the function. I have also tried using return users but can't get it to work. Any help would be appreciated!

app.get('/GetUsers', function (req, res){
    var url = 'mongodb://localhost:27017/users';
    var users = "";
    MongoClient.connect(url, function (err, db) {
        if (err) {
            console.log('Unable to connect to the mongoDB server. Error:', err);
        } else {
            console.log('Connection established to', url);
            // Get the documents collection
            var collection = db.collection('users');
            // Get some users
            collection.find().toArray(function (err, res) {
                if (err) {
                    console.log(err);
                } else {
                    console.log('Got Information from db.');
                }
                //Close connection
                db.close();
                console.log('db closed.');
                users = res;
                console.log(users);
            });
        }
    });
res.send(users);
});

Upvotes: 1

Views: 1914

Answers (3)

Matrix
Matrix

Reputation: 21

Found the answer!!!

I needed to use res.send(users) in my callback after I had closed the database as pointed out by the users suggestions above. HOWEVER, that alone wasn't working as res.send(users) was erroring as it wasn't recognized as a function. I had to use res.send({'matched':users}) and then access my response objects on the client side like this: response.matched.objects etc.

Thanks for your help everyone!

Upvotes: 0

CFrei
CFrei

Reputation: 3627

Just move res.send(users) inside your callback before/after you call console.log(users).

You reused the variable res in the toArray call, so please rename it there: ...toArray(function (err, res)... to ...toArray(function (err, result)... and also in users = res; to users = result;.

Upvotes: 1

Asad
Asad

Reputation: 3160

this is async call it will send the response and will not wait for the database connection function. write res.send in call back function
write your res.send function where you are closing your data base connection.

here is detail How do I return the response from an asynchronous call?

Upvotes: 0

Related Questions