简体   繁体   English

node.js mariasql返回undefined

[英]node.js mariasql return undefined

I believe i have a problem with the Syntax. 我相信我的语法有问题。

By the Function xx the return is undefined :(. Here the Problem in one File. 通过函数xx,返回是未定义的:(。这里是一个文件中的问题。

var Client = require('mariasql');
var inspect = require('util').inspect;


var c = new Client();
    c.connect({
      host: '127.0.0.1',
      user: 'root',
      password: '38nudel5nu',
      db: 'artikel2'
});

var login = function(){

    console.log("LOGIN\n");

    c.on('connect', function() {
       console.log('Client connected');
     })
     .on('error', function(err) {
       console.log('Client error: ' + err);
     })
     .on('close', function(hadError) {
       console.log('Client closed');
     });
}

var end = function(){
    console.log("EXIT");
    c.end();
}


login();

var xx = function(){

c.query("SELECT COUNT(ArtikelID) AS Count FROM artikel")
 .on('result', function(res) {
   res.on('row', function(row) {
    return "YOLO";
   })
   .on('error', function(err) {
   })
   .on('end', function(info) {
   });
 })
 .on('end', function() {
 });

}

var autohaus = xx();

console.log("\n\n --> " + autohaus);

And here is the Output: 这是输出:

[cseipel@myhost testumgebung]$ node skript.js LOGIN [cseipel @ myhost testumgebung] $ node skript.js登录

--> undefined Client connected - >未定义客户端已连接

You're using an asynchronous function as if it were synchronous. 您正在使用异步函数,就好像它是同步的一样。 That's not going to work. 那不行。 You need to pass in a callback to your ArtikelCount function and call the callback once you have the results you want (the typical convention for callbacks is to have the first argument be an error if an error occurred, otherwise it should be null ). 您需要将回调传递给ArtikelCount函数并在获得所需结果后调用回调(回调的典型约定是,如果发生错误,则第一个参数为错误,否则应为null )。

Example: 例:

var ArtikelCount = function(cb) {
    var count,
        error;
    c.query('SELECT COUNT(ArtikelID) AS Count FROM artikel')
    .on('result', function(res) {
        res.on('row', function(row) {
            count = row.Count;
        })
        .on('error', function(err) {
            console.log('Result error: ' + inspect(err));
            error = err;
        })
        .on('end', function(info) {
            console.log('Result finished successfully');
        });
    })
    .on('end', function() {
        console.log('Done with all results');
        cb(error, count);
    }); 
}

Then use it like: 然后使用它像:

wc.ArtikelCount(function(err, count) {
  if (err)
    throw err;
  else
    console.log('Row count', count);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM