javascript - 在 node.js 中返回空值?

标签 javascript node.js

我是 nodejs 的新手。这是我在 nodejs 文件中的代码。 我想使用 json.stringify 将数据从 nodejs 发送到其他 javascript,但我的问题是我得到了 null值(value)... --------------编辑------------------------

我的代码是

function handler ( req, res ) {
        calldb(dr,ke,function(data){
            console.log(data); //successfully return value from calldb                                      
        });
    //i think my problem bellow...
    res.write( JSON.stringify(data)); //send data to other but it's null value
    res.end('\n');
}

function calldb(Dr,Ke,callback){
    // Doing the database query
    query = connection.query("select id,user from tabel"),
        datachat = []; // this array will contain the result of our db query
    query
    .on('error', function(err) {
        console.log( err );
    })
    .on('result', function( user ) {
        datachat.push( user );
    })
    .on('end',function(){
        if(connectionsArray.length) {
            jsonStringx = JSON.stringify( datachat );
            callback(jsonStringx); //send result query to handler
        }
    });

}

如何解决这个问题?

最佳答案

您将需要使用回调,直接返回数据只会返回 null,因为 end 事件处理程序会在所有数据准备就绪后调用。尝试类似的东西:

function handler ( req, res ) {
    calldb(dr, ke, function(data){
       console.log(data);
       res.write( JSON.stringify(data)); 
       res.end('\n');
    });
}

function calldb(Dr,Ke, callback) { 

    var query = connection.query('SELECT id,userfrom tabel'),
        datachat= []; // this array will contain the result of our db query

    query
     .on('error', function(err) {
        console.log( err );
     })
     .on('result', function( user ) {
        datachat.push( user );
     })
     .on('end',function() {
        callback(datachat);
    }); 

}

关于javascript - 在 node.js 中返回空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16370367/

相关文章:

javascript - 查找 cookie 字符串中存在的 cookie - javascript

javascript - Cookie 被设置到不同的域(Node.js、Angular)

javascript - JSON.parse( ) 的数值变化

php - 使用 JQuery 或 Javascript 刷新图像

javascript - 满足条件时关闭 Bootstrap 模式

javascript - 弹出窗口中的溢出滚动条不起作用( Bootstrap )

javascript - 如何结束 'pg-promise'应用程序

javascript - 如何测试使用 module().controller 创建的 angularjs Controller ?

javascript - 在IE中,脚本不会更改div的innerhtml

node.js - 在 express GraphQL 中解析嵌套数据