0

I'm a NodeJS beginner and actually I try to work with a NoSQL Database for building a simple login via. Digest Authentication. I also created an module called "users" wich is loaded in my application.

Now when I try to call the data results inside the callback function I get my correct data. In the same callback I assign the returned data to the variable records. When I call the variable outside I will get the result null - where is the error?

var dbdriver = require('nosql'),
dbfile = dbdriver.load("./db.nosql"),
records = null

dbfile.top(1000).callback(function(err, response) {
    (function(users) {
        records = users
        console.log(users) // Here i get the wanted result
    })(response)
})

console.log(records) // Here the result is empty

thank you very much :)

Community
  • 1
  • 1

2 Answers2

1

Since the you are calling console.log(users) inside the callback, the value is reflected correctly. And this is a behavior of asynchronous calls in javascript. So the last line console.log(records) would probably be run first before the callback executes and so records up to this point does not have any value. So I would suggest that you make the a function that does something on users and call it inside the callback.

var dbdriver = require('nosql'),
dbfile = dbdriver.load("./db.nosql"),
records = null

dbfile.top(1000).callback(function(err, response) {
    (function(users) {
        //records = users
        //console.log(users) // Here i get the wanted result
        doSomethingToUsers(users); 
    })(response)
})

function doSomethingToUsers(users) {
 // do something to users
}

//console.log(records) // Here the result is empty
carloliwanag
  • 348
  • 3
  • 12
0

Looks like a timing issue to me. When console.log(records) in the outer scope gets called before the (async) callback function was called, records contains exactly the value that was initially assigned (records = null).

Only after calling the async callback, the records variable will be set.

Does this help?

Konstantin A. Magg
  • 1,106
  • 9
  • 19