creationix / nstore

nStore is a simple, in-process key/value database for node.js
MIT License
392 stars 31 forks source link

can only access document properties using bracket syntax and not '.' syntax #5

Closed bryanwb closed 13 years ago

bryanwb commented 14 years ago

I am trying to access the document properties with a closure variable

var sys = require('sys');
var nstore = require('nstore');
var name;
var users = nstore('users.db')
users.save('creationix', {name: 'creationix', password: 'password'});
// when I check users.db, this record is there

users.get('creationix', function(err, doc, meta) { 
    name = doc.name;
    sys.puts(name);
    //displays name "creationix"
});

// some time later

sys.puts(name);
// returns undefined

it does work if I do this

name = doc[name];

why is this?

creationix commented 14 years ago

Either your example code is missing something or you're misunderstanding how async functions work.

In your example, the users.get callback is the last thing executed. Everything is synchronous blocking code (users.save should have a callback btw) So sys.puts(name) is executed before name = doc.name.

The best way to understand it is to put console.debug() statements all throughout your code and see what order things actually happen.

Also you should have a callback on users.save and not call users.get till after the callback has come back. If not you have a race condition and it will only work under certain conditions. Trust me, these are really nasty to track down.

For more about how to chain async functions see my Step library. Or simply nest callbacks.

bryanwb commented 14 years ago

hmm, I must be doing this wrong. Sorry for the trouble

creationix commented 14 years ago

no trouble at all, let me know if you figure it out.