Sunday 21 May 2017

understanding callbacks with a specific example.

Hey folks, I just got back from my first hackathon, and I was on a team using node-mysql to get data from a mysql database then return that data for front end use. We ran into an issue and ultimately decided to solve our problem a separate way, but I have a specific question about this particular section of code, and understanding how to get it to work.It took a bit to realize there was an async aspect of node because none of my teammates were familiar with it. We noticed things weren't printing in the order we expected, and we found out callbacks were needed but we could not implement them properly ultimately. I don't want to let this go though without understanding. I read multiple articles on call backs, and I couldn't wrap my head around this which is disappointing me.getData(input){ var output = 0; var mysql = require('mysql'); var connection = mysql.createConnection(); //other connection and server setup here connection.connect(function(err){ connection.query('SELECT * FROM table WHERE tableData = input', function(err,result){ if(err) throw err; output = result //console.log(result) connection.end }//connection.query close }//connection.connect closed return output; } start(){//for testing the above function var arr = getData(); console.log(arr) //query data is expected as the result, but 0 is returned } start();//run the start function Can anyone help me figure this out? I kind of understand at a surface level what's going on with asynchronous code, but I don't understand how to make it work with node's syntax, and I feel like node related documentation is pretty bad, or I'm not smart enough for it (or maybe both).

Submitted May 22, 2017 at 01:27AM by SimplestMachine

No comments:

Post a Comment