0

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?

Cris
  • 12,124
  • 27
  • 92
  • 159

1 Answers1

1

You need to use callbacks more appropriately.

A more traditional listItems function would be

exports.listItems = function(done) {
    Ticket.find({}, done);
}

Then, in list, you could do:

exports.list = function(req,res) {
    db.listItems(function(err,items){
        console.log("Items:"+items);
        res.render('list', { title: title, items:items });
    });
}

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.

bevacqua
  • 47,502
  • 56
  • 171
  • 285