-1

I have node.js with express3.

For mongodb usage, I required mongo-lazy package.

So, I have simple GET router:

var db = require('mongo-lazy').open({
    db: 'somedb',
    host: '127.0.0.1',
    port: 27017,
    user: 'someuser',
    password: 'somepassword'
});

var result={};

db.person.findAll({}, function (err, persons) {
    result.err=err; 
    result.persons=persons;
    console.log("__0: " + typeof persons);
    console.log("__1: " + typeof result.persons);
});
console.log("__2: " + typeof result.persons);

if (!result.err) res.send("test");

And the console is:

Express server listening on port 3000
__2: undefined
GET /mongo 200 1508ms - 5
__0: object
__1: object

So, the questions are:

  1. Why node calls __2 first, and __0, __1 after __2, but the line order is other?
  2. How to put err, persons into the result?
fend25
  • 143
  • 1
  • 6
  • 1
    Because `db.person.findAll` is **asynchronous**. Have a look at the [first part of my answer here](http://stackoverflow.com/a/14220323/218196). Anything that has to work with the results has to be *inside* the callback. – Felix Kling Mar 31 '13 at 12:40

1 Answers1

1

findAll() is an asynchronous call and the function you pass to it is the callback to execute when the function returns. Rearrange like this to get the expected behaviour;

db.person.findAll({}, function (err, persons) {
    if (!err) res.send(persons);
});
Jivings
  • 22,834
  • 6
  • 60
  • 101