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

196
Vistas
JS async function returning undefined although calling it inside an asynchronous function

I am using nodeJs Express and I have an async function which is used in another function.

here is my code:

/* get user info */
const getUserInfo = async (req) => {
    let userID = req.cookies.userId;
    if(!userID) return null;
    await connection.query('SELECT * FROM users WHERE id = ' + userID,
        function (err, rows, fields) {
            if (err) throw err
            // if user not found
            if (rows.length === 0) {
                return null;
            }
            // if user found
            else {
                return rows[0];
            }
        });
}
/* display dashboard page */
router.get("/", async function (req, res, next) {
    let userInfo = await getUserInfo(req);

    console.log(userInfo) // It's result is undefined


    if (userInfo) {
        res.render('dashboard/profile', {
            fullName: userInfo.fname + " " + userInfo.lname,
            email: userInfo.email,
            phone: userInfo.phone,
        });
    }
    else {
        res.render('authentication/register', {
            title: 'ثبت نام',
        });
    }

});

how to resolve this problem? I need userInfo retun me some data.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

await is only useful if the value on the right-hand side is a promise.

connection.query is taking a callback function, which implies it isn't returning a promise.

You need to either:

  • Find out how to make the API you are using return a promise (if that is possible)
  • Wrap the callback in a promise
  • Replace the API with one that supports promises natively

You also need getUserInfo to have a return statement of its own.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You have to return some value from your getUserInfo function

If connection query doesn't support promise you should wrap it like this

/* get user info */
const getUserInfo = async(req) => {
  let userID = req.cookies.userId;
  if (!userID) return null;
  return new Promise((resolve, reject) => {
    connection.query('SELECT * FROM users WHERE id = ' + userID,
      function(err, rows, fields) {
        if (err) {
          reject(err)
          return;
        }
        // if user not found
        if (rows.length === 0) {
          resolve(null)
        }
        // if user found
        else {
          resolve(rows[0]);
        }
      });
  });
}
about 4 years ago · Juan Pablo Isaza 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