-1
  1. get_version.js
const mysql = require('mysql');
var version = '';

function execute() { 
    connection.query('SELECT VERSION() as version', function (error, results, fields) {
        if (error) throw error;
        version = results[0].version;
        console.log(version); // 8.0.15
    });
}
  1. routes/index.js
const get_version = require('./get_version')

router.post('/test',function (req, res, next) {
  var mysqlVersion = get_version.execute();
  **console.log(mysqlVersion);** // output: undefined, i want 8.0.15
});

First of all, this question is similar to other questions,
but it's so hard to understand as other people's questions.

This code cannot be executed.
I know that this problem requires understanding of the callback function.

What is the most similar way to execute the code for this issue, like ruby, php?
This may be a strange question,
but I think there's a way to do it as similarly as possible.

I just want to know the ways of people who know more than I am a beginner.

useeffect
  • 59
  • 1
  • 5
  • 1
    As it stands, you cannot get the value, because `execute` neither accepts a callback nor returns anything (e.g. a promise of the value). – jonrsharpe Oct 27 '20 at 18:24

1 Answers1

0

It’s not quite so simple in node because the call to get_version.execute() in non blocking.

So you code moves on before the query finishes and results in undefined.

Make the router.post callback an asynchronous function and await the response from any code that calls for blocking resources such as databases etc and start working forwards from there making things use async/await as necessary.

This should help

var connection = mysql.createConnection({
  host: "127.0.0.1",
  user: "root",
  password: "rootpassword",
});

connection.connect(err => {
  if (err) throw err;
  console.log("Connected!");
});

const getDatabaseVersion = async () => {
  return new Promise((resolve, reject) => {
    connection.query("SELECT VERSION() as version", (error, results, fields) => {
      if (!error) {
        resolve(results[0].version)
      } else {
        reject()
      }
    })
  });
}

router.get('/', async(req, res, next) => {
  const dbver = await getDatabaseVersion()
  res.send({message: "OK", databaseVersion: dbver});
});