Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

411
Views
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 looks like the request is async, because my request happens after that my post request returns the value.

How do I set an await for request?

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
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Change the implementation of queryDatabase function to return a promise. Any function that returns a promise can be awaited.

function queryDatabase(userQuery){
     return new Promise((resolve,reject) => {
        connection.query(userQuery, function(err, result){
            if(err){
              reject(err);
            }
            console.log("before");
            resolve(result);
        }); 
     }); 
}



app.post('/signin', async function(request, response){
    var query = await queryDatabase("SELECT EMAIL FROM MEMBER WHERE ID_MEMBER = 3");
    console.log(query);
    console.log("after");
    response.end(query, 200);
});
about 4 years ago · Santiago Trujillo Report

0

Welcome to Node.js where everything is intended to be asynchronous and unless you explicitly structure your code in a way that cascades one event to another there's no obligation on the part of the code to run in any particular order at all.

I'd strongly recommend picking up on Promises as a way of organizing code if you're not familiar with this concept. This wraps up a lot of tricky programming into some neat, tidy methods, and makes chaining, fan-out and fan-in actually pretty simple.

For example, rewritten with Sequelize, a database layer that uses promises:

function queryDatabase(userQuery){
   console.log("before");

   return connection.query(userQuery);
}

You return the promise, and that's used to chain. If you don't you must accept a callback argument and chain that through. Return values are largely ignored:

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

You can see there's a lot more cruft already, and even more if you needed to build off of that. Inserting optional steps in callback driven code is tricky.

Promises make your code end up looking like this:

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

It's also trivial to patch in error handling in one place with catch to handle errors.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!