从函数返回结果(javascript,nodejs)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7255956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:30:33  来源:igfitidea点击:

return results from a function (javascript, nodejs)

javascriptnode.jsasynchronous

提问by profesoralex

Could anyone help me with this code? I need to return a value form a routeToRoom function:

任何人都可以帮助我使用此代码吗?我需要从 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"));

But I get always: 0

但我总是得到:0

I guess return roomId;is executed before roomId=results.creationix.room. Could someone help me with this code?

我猜return roomId;是之前执行的roomId=results.creationix.room。有人可以帮助我使用此代码吗?

回答by Raynos

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);    
});

You need to use callbacks. That's how asynchronous IO works. Btw sys.putsis deprecated

您需要使用回调。这就是异步 IO 的工作原理。顺便说一句sys.puts已弃用

回答by Simone Gianni

You are trying to execute an asynchronous functionin a synchronous way, which is unfortunately not possible in Javascript.

您正在尝试以an asynchronous function同步方式执行,不幸的是not 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.

正如您猜对的那样,roomId=results.... 在从数据库加载完成时执行,这是异步完成的,因此在您的代码恢复完成后。

Look at this article, it talks about .insert and not .find, but the idea is the same : http://metaduck.com/01-asynchronous-iteration-patterns.html

看这篇文章,讲的是.insert and not .find,但是思路是一样的:http: //metaduck.com/01-asynchronous-iteration-patterns.html