Get node.js neDB data into a variable

Callbacks are generally asynchronous in JavaScript meaning you can not use assignment operator, consequently you do not return anything from the callback function.

When you call an async function execution of you programme carries on, passing the 'var x = whatever' statement. The assignment to a variable, the result of whatever callback is received, you need to perform from within the callback itself... what you need is something in the lines of ...

var x = null;
db.find({ }, function (err, docs) {
  x = docs;
  do_something_when_you_get_your_result();
});

function do_something_when_you_get_your_result() {
  console.log(x); // x have docs now
}

EDIT

Here is a nice blog post about asynchronous programming. And there is a lot more resources on this topic that you can pick up.

This is a popular library to help with async flow-control for node.

P.S.
Hope this helps. Please, by all means ask if you need something clarified :)


I ran into the same problem. In the end I used a combination between async-await and a promise with resolve to solve it.

In your example the following would work:

var x = new Promise((resolve,reject) {
    db.find({ }, function (err, docs) {
        resolve(docs);
    });
});

console.log(x);