0

function x() is supposed to return result variable but it is returning undefined also console.log(result) is printing on the terminal. Also return test1 is showing undefined but return test2 is returning correctly.

const mysql = require("mysql");

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'p_two',
    port: '3306'
});

connection.connect((error) => {
    if (error) {
        console.log(error)
    }
    else {
        console.log("Mysql connected")
    }
});

function x() {
    const con = connection.query("SELECT * FROM blog WHERE id = 1", (error, results) => {
        if (error) {
            console.log(error)
        }
        else {
            console.log(results)
            return results
        };
        // return "test1"
    });
    // return "test2"
}

console.log(x())
vision
  • 1
  • The only `return` statement in `x` is commented out. The `return` statement in the anonymous function you pass to `query` is not in `x`, it is in the anonymous function. – Quentin Jul 05 '20 at 08:35
  • I do not find that question duplicate. – vision Jul 05 '20 at 08:45
  • But your comment is somehow useful, still dont understand the solution. – vision Jul 05 '20 at 08:46
  • "I do not find that question duplicate" — Well, it is. And the solutions are explained in 105 different ways on it. – Quentin Jul 05 '20 at 08:47
  • Okay, I thought that question is related to Ajex but mine is Mysql. I am reading that question. THanks – vision Jul 05 '20 at 08:50
  • Asynchronously called callbacks are asynchronously called callbacks no matter if they are playing with HTTP, databases or something else. – Quentin Jul 05 '20 at 08:51
  • I tried some methods but I am not good in javascript, and don't know how to implement async/await in this case. Terminal is now showing Promise { } – vision Jul 05 '20 at 09:12
  • https://stackoverflow.com/questions/49938266/how-to-return-values-from-async-functions-using-async-await-from-function – Quentin Jul 05 '20 at 09:13

0 Answers0