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

195
Visualizações
Cant access username before Intialization when I try to use an async function to call a promise

What I'm trying to do here is call the username from the database from the cookie, I tried to just call it though a regular function, but that doesn't work since I have to wait on the data. then after send the data to the webpage. but my issue is just getting the data itself. I don't really have much experince with promises, so I'm trying to figure out what's happening here. thanks for the help.

async function user(req, res) {
  let key = req.cookies['cookie']
  return new Promise((resolve, reject) => {
    connection.query('SELECT * FROM accounts WHERE `key` = ?', [key], (error, results, fields) => {
      if (error) {
        return console.log(error)
      }
      if (results.length > 0) {
        resolve(results[0].username)
      }
    });
  }
  )
}

async function grabinfo(req, res) {
  res.render('dashboard', { title:'Dashboard', username: username});
  const username = await user(req, res)
}


module.exports.grabinfo = grabinfo

The Error

(node:1463495) UnhandledPromiseRejectionWarning: ReferenceError: Cannot access 'username' before initialization
    at Object.grabinfo (/home/ubuntu/nodeprojects/website/modules/dashboard.js:45:58)
    at /home/ubuntu/nodeprojects/website/router/app.js:37:15
    at Layer.handle [as handle_request] (/home/ubuntu/nodeprojects/website/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/ubuntu/nodeprojects/website/node_modules/express/lib/router/route.js:144:13)
    at Route.dispatch (/home/ubuntu/nodeprojects/website/node_modules/express/lib/router/route.js:114:3)
    at Layer.handle [as handle_request] (/home/ubuntu/nodeprojects/website/node_modules/express/lib/router/layer.js:95:5)
    at /home/ubuntu/nodeprojects/website/node_modules/express/lib/router/index.js:286:22
    at Function.process_params (/home/ubuntu/nodeprojects/website/node_modules/express/lib/router/index.js:348:12)
    at next (/home/ubuntu/nodeprojects/website/node_modules/express/lib/router/index.js:280:10)
    at SendStream.error (/home/ubuntu/nodeprojects/website/node_modules/serve-static/index.js:121:7)
(node:1463495) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside                                  of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the                                  node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli                                 .html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1463495) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections t                                 hat are not handled will terminate the Node.js process with a non-zero exit code.
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

async function grabinfo(req, res) {
  const username = await user(req, res)

  res.render('dashboard', { title:'Dashboard', username: username})
}
about 4 years ago · Juan Pablo Isaza Relatório

0

The error message clearly says. You are using the username constant before defining it. javascript works top to bottom, not bottom to top so first initialize username then use it.

async function user(req, res) {
  let key = req.cookies['cookie']
  return new Promise((resolve, reject) => {
    connection.query('SELECT * FROM accounts WHERE `key` = ?', [key], (error, results, fields) => {
      if (error) {
        return console.log(error)
      }
      if (results.length > 0) {
        resolve(results[0].username)
      }
    });
  }
  )
}

async function grabinfo(req, res) {
  const username = await user(req, res);
  res.render('dashboard', { title:'Dashboard', username: username});
  
}


module.exports.grabinfo = grabinfo
about 4 years ago · Juan Pablo Isaza 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