Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

415
Vistas
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
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

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);
});
over 4 years ago · Santiago Trujillo Denunciar

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.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda