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.

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

--> undefined Client connected

Answers


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).

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

Need Your Help

form post variables in controller

php codeigniter jquery frameworks

this is my javascript view and the controller am calling.

facing strange issue with xcode project opening

iphone objective-c ios5 xcode4.2

My project directory is: Developer/Examples/MyPhoneGame/MyPhoneGame.xcodeproj

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.