Question

I'm having alot of trouble getting couchdb's response handlers to do anything useful with node.js and now.js. My aim is to call back to a client or group with certain information that's been found and also sent from a client.

everyone.now.login = function(){
var username = this.now.lusername;
var password = this.now.lpassword;
var test;
db.get(this.now.lusername, function (err, doc, test, username) {
    if (err) {
        console.log(+ username + " doesn't exist!");

    } else  {
        console.log('Found user!');
        console.log(doc);
        test = 1;
   }
    });
    console.log(test);
}

I'm using test as an example here. I declare it outside db.get, assign a value inside to feed back but when console.log is run outside it doesn't have a value.

Am I simply not getting it or is something wrong?

(I do release I can use doc.(whatever value) but there is a particular variable i wanted to pass on back to the client outside of this call)

Was it helpful?

Solution

The test variable will not have a value in the console.log because the CouchDB response has not arrived yet. Your login function executes the following steps.

  1. Set some variables (username, password, and test is undefined)
  2. Begin a CouchDB fetch (for this.now.lusername) with a function assigned to run when it is complete
  3. Run console.log(test) which is still undefined
  4. The CouchDB response completes, and your function from step 2 runs

What I do for things like this is use function calls.

everyone.now.login = function(){
  var username = this.now.lusername;
  var password = this.now.lpassword;

  db.get(this.now.lusername, function (err, doc, test, username) {
    if (err) {
        console.log(+ username + " doesn't exist!");

    } else  {
        console.log('Found user!');
        console.log(doc);
        login_complete(doc);
   }
  });

  function login_complete(doc) {
    console.log('The login finished! Doc is ' + doc)
  }
}

This way the code still looks correct (the "story" of the code mostly flows from top to bottom), but it also executes correctly (the login_complete() function runs only after the login is actually complete).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top