有人可以帮我这个代码吗?我需要从routeToRoom函数返回一个值:
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"));
但我总是得到:0
我猜
return roomId;
在roomId=results.creationix.room
之前执行。有人可以帮我这个代码吗? 最佳答案
function routeToRoom(userId, passw, cb) {
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;
}
cb(roomId);
});
});
}
routeToRoom("alex", "123", function(id) {
console.log(id);
});
您需要使用回调。这就是异步IO的工作方式。 Btw
sys.puts
已弃用关于javascript - 从函数返回结果(javascript,nodejs),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7255956/