Nested Function Return Values, Where I am wrong in this code?

Hi All,

I am using Meteor.JS and pcel:mysql to fetch the mysql result from the method and passing it to the helper.

In my Method, the method is getting executed fine and using connection.query I am able to log the mysql rows in the server side console.

This is what my code looks like:

	if (Meteor.isClient) {

	  Meteor.call('mysqltestcall1', function(error, result){
		Session.set('myMethodResult', result);
	  });
	  
	  Template.hello.helpers({
		data2: function(){
		  return Session.get('myMethodResult');
		}
	  });

	}

	if (Meteor.isServer) {


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

	connection.connect();


	Meteor.methods({
	'mysqltestcall1': function(){
	var returnresult = 'test value';
	connection.query('SELECT * FROM players', function(err, rows, fields) {
		if (err) throw err;
		console.log(rows);
		returnresult = rows;
	});

	return returnresult;
	}

	});


	}

I am getting the value as “test value”, but not rows JSON data. Can anyone help me out.

I thing I am not using the variable correctly is in the nested function.

Hi,
i guess connection.query => async code.
Use Meteor._wrapSync or meteorhacks:async.

The connection query is happening asynchronously and is non-blocking (the query is started but not completed before it moves to the next line of code), so return returnresult still has the value ‘test value’ when it is returned.

So, how can you make it wait for something that is still yet to happen, i.e. something that is going to happen in the future?

Meteor.methods({
	'mysqltestcall1': function(){

   // use the node fibers npm
     var Future = Npm.require('fibers/future');

   // make some new future
     var fut = new Future();
	
	 connection.query('SELECT * FROM players', function(err, rows, fields) {
		if (err) throw err;
		console.log(rows);

            // when this callback eventually happen, returns rows 
		fut.return(rows);
	 });
 
     // wait for something from the future
	 return fut.wait();
	}

	});

You might also want to look at http://docs.meteor.com/#/full/meteor_wrapasync

3 Likes

Thanks Nguyen and Garrilla,

Today I got new things to discover, Thanks for sharing your knowledge.

Garrilla, Your code works like charm :smile:, Thank you very much.

I will also study wrapasync

Regards,
Manu

Hi Again,

I was trying to use Meteor WrapSync like this :

		'mysqltestcall2': function(){
		
		data1 =  function(){
				
			connection.query('SELECT * FROM players', function(err, rows, fields){
			if (err) throw err;
	    	console.log(rows);
		 });

		return rows;

		};
	 
		 var returndata =  Meteor.wrapAsync(data1);

		 console.log(returndata);
		}

In the Server Side Console I am getting Output as : [Function]

I am new to this Stack, Sorry If I am asking silly question.

Thanks for your kind support.

Regards,
Manu