I am trying to do a nested query with MySql, put the result inside a variable and send over http, but the program always run console.log("test 2:"+rpsData); before the query finish. I already tried this, but still getting the same problem.
const express = require('express')  
const app = express()
const mysql = require('mysql');
const Connection = require('mysql/lib/Connection');
const Promise = require('bluebird');
Promise.promisifyAll([
    Connection
]);
const connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'root123',
  database : 'mygallery'
});
app.get('/posts', function(request, response) {
    var rpsData;
  connection.connectAsync()
  .then(function() {
    connection.query('SELECT * FROM post WHERE approved = 1', function(err, rows, fields) {
      if (err) throw err;
      rpsData = rows;
      for (var i in rows) {
        connection.query('SELECT * FROM image WHERE postCode = ?', [rpsData[i].postCode], function(err, rows, fields) {
          if (err) throw err;
          rpsData[i].image = rows;
          console.log("test 1:"+rpsData);
        });
      }
    });
  })
  .then(function() {
    response.send(rpsData);
    console.log("test 2:"+rpsData);
  })
  .catch(function(error) {
    console.error('Connection error.', error);
  });
});
 
     
    