0

I just started with crossbar and nodejs. I have a PHP background. I know that mysql on nodejs is async so I added a callback but i can't get the callback to return a value to the register method from crossbar. What would be the correct way to handle this?

var autobahn = require('autobahn');
var mysql = require('mysql');
var q = require('q');

var connection = new autobahn.Connection({
   url: 'ws://127.0.0.1:8080/ws',
   realm: 'realm1'}
);

connection.onopen = function (session) {

   function dologin (cb) {

        var connection = mysql.createConnection({
            host     : 'localhost',
            user     : 'xxxxx',
            password : 'xxxxx',
            database : 'xxxxx'
        });
         connection.connect();

         connection.query('SELECT * from users LIMIT 0,2', function(err, rows, fields) {
            if (!err){
               cb("Done");
            }else{
               cb('Error while performing Query. ');
            }

         });
     }
   function login (args) {
        return dologin(function(response){

           return "status: "+response;
        });
   }

   session.register('com.cms.login', login).then(
      function (reg) {
         console.log("Login registered");
      },
      function (err) {
         console.log("failed to register procedure: " + err);
      }
   );
};

connection.open();
  • Async, async, async. You can't synchronously return a value that comes in an async callback. You just can't. The result can ONLY be used in the callback. A variant of this question is asked dozens of times per day. – jfriend00 Sep 21 '15 at 18:12
  • possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – jfriend00 Sep 21 '15 at 18:13
  • For an example of how to do slow returns in JavaScript with WAMP procedures see https://github.com/tavendo/AutobahnPython/blob/master/examples/twisted/wamp/rpc/slowsquare/backend.js – gzost Sep 24 '15 at 12:45

0 Answers0