I have a node.js app that uses mongoose to connect to
a mongodb; i need to select all the documents inserted and i
i’ve problems with async stuff.
I’ve made a model with the following function:
exports.listItems=function() {
Ticket.find({}, function(err,tkts) {
console.log(tkts);
return tkts;
});
}
I correctly see the value of “tkts”, but when i call it from:
exports.list = function(req,res) {
var items=db.listItems();
console.log("Items:"+items);
res.render('list', { title: title, items:items });
}
defined in app.js as:
app.get('/list', routes.list);
items is undefined (i think because of non-async definition of db.list()).
What am i doing wrong and how can it be corrected?
You need to use callbacks more appropriately.
A more traditional
listItemsfunction would beThen, in
list, you could do:Because of the asynchronous nature of Node.JS, you should always pass (and expect) a callback in your functions. So that you can defer execution if something asynchronous is executed.
Also: be sure to check out async, its an insanely good and easy-to-use library, that will simplify complex async scenarios in a breeze.