A Server.js response from two MySQL tables.

One thing that is a bit challenging is how to tespond from Server.Js when you have to get data out of two MySQL tables. Well it took a little digging but I finally found a solution.

This little bit of code write here. Uses the Q module from node. You can install it using npm install --save q .

Add this little code to your Server.Js.

app.get('/weather', function(req,res) {
 var res = res;
 var weather = {};

var deferredTandH = Q.defer();
var deferredPressure = Q.defer();

mysql.readLatestValues('BMP180', 1, deferredPressure.makeNodeResolver());
mysql.readLatestValues('TemperatureHumidity', 1, deferredTandH.makeNodeResolver());

Q.all([deferredTandH.promise, deferredPressure.promise]).then(function(results){
 weather.temperature = results[0][0].temperature;
 weather.humidity = results[0][0].humidity;
 weather.pressure = results[1][0].Pressure; 

In the code above there is a table named “BMP180” and “TemperatureHumidty”. These are the same ones shown in the previous post on setting up Server.Js.

That should do it. Now when both reads return you will process the promise in the then() method and you can return a single response.


About isaacdrose

Software Engineer. All around nerdy guy.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: