Reputation: 752
I've got two .js files on the server-side: app.js
and manageDB.js
. I would like to retrieve data from MongoDB and use it on the client-side.
manageDB.js:
exports.getClients = function() {
db.clients.find(function(err, docs) {
if (err) {
console.log(err);
} else {
return docs;
}
});
};
And I would like to do something like this in app.js:
app.get('/', function(req, res) {
var clients = manageDB.getClients();
res.render('index.html', {myClients: clients});
});
but clients are undefined because of asynchronism. If I log docs
in the console within getClients
function (manageDB.js file) it is ok but if I try to console.log(manageDB.getClients())
within app.js file - it doesn't work. I would appreciate any help.
Upvotes: 1
Views: 233
Reputation: 1843
As you have noted, JS is async. db.clients.find
knows this, so it requires a callback, which is exactly what you need to do too. If you are providing real code, it could be simplified to this:
// manageDB.js
// Note I added `module`. It is best practice
module.exports.getClients = function(callback) {
db.clients.find(callback);
};
//app.js
app.get('/', function(req, res) {
manageDB.getClients(function(err, docs) {
if (err) throw new Error(err);
res.render('index.html', { myClients: docs });
});
Or if you need to do some other processing in manageDB.js
:
// manageDB.js
module.exports.getClients = function(callback) {
db.clients.find(function(err, docs) {
if (err) { return callback(err); }
// do more stuff
return callback(null, docs);
});
};
//app.js
app.get('/', function(req, res) {
manageDB.getClients(function(err, docs) {
if (err) throw new Error(err);
res.render('index.html', { myClients: docs });
});
Upvotes: 2
Reputation: 1553
As you've already mentioned, Node.JS is asynchronous. One way of working with this is passing the data via a call back. Others include promises and coroutines.
For example:
module.exports.getClients = function(callback) {
db.clients.find(function(err, docs) {
if (err) {
console.log(err);
return callback(err);
}
return callback(null, docs);
});
};
And then use this:
app.get('/', function(req, res) {
manageDB.getClients(function(err, clients) {
if(err) {
// Handle error
} else {
res.render('index.html', {myClients: clients});
}
});
});
Upvotes: 2