Could anyone help me with this code? I need to return a value form a routeToRoom function:
var sys = require('sys');
function routeToRoom(userId, passw) {
var roomId = 0;
var nStore = require('nstore/lib/nstore').extend(require('nstore/lib/nstore/query')());
var users = nStore.new('data/users.db', function() {
users.find({
user: userId,
pass: passw
}, (function(err, results) {
if (err) {
roomId = -1;
} else {
roomId = results.creationix.room;
}
}
));
});
return roomId;
}
sys.puts(routeToRoom("alex", "123"));
But I get always: 0
I guess return roomId;
is executed before roomId=results.creationix.room
. Could someone help me with this code?
You are trying to execute
an asynchronous function
in a synchronous way, which is unfortunatelynot possible in Javascript
.As you guessed correctly, the
roomId=results
.... is executed when the loading from the DB completes, which is done asynchronously, so AFTER the resto of your code is completed.Look at this article, it talks about
.insert and not .find
, but the idea is the same : http://metaduck.com/01-asynchronous-iteration-patterns.htmlYou need to use callbacks. That's how asynchronous IO works. Btw
sys.puts
is deprecated