Saturday, 29 April 2017

How do we use Async, and what is the best way in nodeJS

I'm trying to pass a query to my database, then send the result to my client side, but it's looking like the request is async, because my request happen after that my post request return the value, so the question is how do I set an await for request?

here's a sample of my code!

my database connection

var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password : 'my_password',
database : 'MEETME'
});

connection.connect(function(err){
    if(err){
    console.log("error while connecting to database");
    console.log(err.code);
    }
});

//function that query database <-------

function queryDatabase(userQuery){
       connection.query(userQuery, function(err, result){
            if(err){
           throw err;
        }
       console.log("before");
        return result;
    }); 
}

and this is my post request

//POST
app.post('/signin', function(request, response){
    var query = queryDatabase("SELECT EMAIL FROM MEMBER WHERE ID_MEMBER = 3");
    console.log(query);
    console.log("after");
    response.end(query, 200);
});

the result in the console is:

undefined
after
before



via MathieuAuclair

No comments:

Post a Comment