0

I am new to Node JS and i want to create a website with expressJS and Node.JS and i want to two create a async query function, to get the result in a variable - so that i can use this function for all queries.

I create a db.js with the following code:

const mysql = require("mysql")

const connection = mysql.createPool({
host: "...",
user: "...",
password: "...",
database: "..."
})

var sql_statement = {...}

function queryResult(function(statement) { //Async function

    connection.getConnection(function (error, connection) {
        if (error) throw error

        connection.query({...}), function (error, results)
            connection.release()
            return results
        })
    })
}

var output = queryResult(sql_statement)
console.log(output)

but it doesn't work this in example works and it shows me the result in the console:

//code...
connection.getConnection(function (error, connection) {
    if (error) throw error

    connection.query({...}), function (error, results)
        console.log(results)

        connection.release()
    })
})
//code...

info: the website is very simple and and i want to use this function to output my SQL data in expressJS on the website like this:

//code...
app.get("/", function (req, res) {
    var sql_statement = {...} //SQL stmt for index.html
    entries = queryResult(sql_statement)

    res.render("index.html", {
        title: "Home",
        show_entires: entries  
}

app.get("/articles", function (req, res) {
    var sql_statement = {...} //SQL stmt for articles.html
    entries = queryResult(sql_statement)

    res.render("article.html", {
        title: "Articles",
        show_entires: entries  
}
//code...
andreaslacza
  • 19
  • 1
  • 5
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Patrick Hund Feb 14 '18 at 14:47
  • This is a very common beginner mistake, you are trying to return the result of an asynchronous call as if it were synchronous. Take a look here: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Patrick Hund Feb 14 '18 at 14:48
  • i have updated my question – andreaslacza Feb 14 '18 at 15:12

0 Answers0