Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

265
Visualizações
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.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

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.

over 4 years ago · Santiago Trujillo Relatório

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]);
        }
      });
  });
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda