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

115
Visualizações
Java Script Promises

What I am trying to do:

This HTTP call updates the password in the database. I send the new password to go get hashed and salted in getHashedPassword(), and this works, at least according to the console.log where a hash number is printed.

Problem: body data-field does not get updated when I reassign it with the result from the promise, proven by the console log right outside the promise. So thus in the database the new literal string password gets updated but not hash. I'll provide output and pictures in case my explaining is confusing.

    router.put('/:id', (req, res) => {
        
          getHashedPassword(req.body.password01).then( result => {
            console.log('this is the hashed', result);
            req.body.password01 = result;
          })
          console.log('new passwords', req.body.password01);
          BasicUser.findByIdAndUpdate(req.params.id, req.body)
            .then(user => res.json({ msg: 'Updated successfully' }))
            .catch(err =>
              res.status(400).json({ error: 'Unable to update the Database' })
            );
        
        });

Console.logs:

new passwords helloagain339
this is the hashed $2b$10$fPw/bHW69mnyltWh0Qn3T.hKIsxbhgTt8/OGxOQXVVRDpTICqZCy.
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Okay, the issue is that BasicUser.findByIdAndUpdate runs before the getHashedPassword promise can resolve and return the response so that it can be passed on to findByIdAndUpdate. The way to solve it is use async/await or put second promise within the callback of the first one.

Async / Await approach
router.put("/:id", async (req, res) => {
  try {
    req.body.password01 = await getHashedPassword(req.body.password01);
    console.log("new passwords", req.body.password01);
    const user = await BasicUser.findByIdAndUpdate(req.params.id, req.body);
    res.json({ msg: "Updated successfully" });
  } catch (error) {
    res.status(400).json({ error: "Unable to update the Database" });
  }
});
Nested callback approach
router.put("/:id", (req, res) => {
  getHashedPassword(req.body.password01).then((result) => {
    console.log("this is the hashed", result);
    req.body.password01 = result;
    console.log("new passwords", req.body.password01);
    BasicUser.findByIdAndUpdate(req.params.id, req.body)
      .then((user) => res.json({ msg: "Updated successfully" }))
      .catch((err) =>
        res.status(400).json({ error: "Unable to update the Database" })
      );
  });
});
P.S: I would recommend the async-await approach
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use async/await to make code more readable like this

router.put('/:id', async (req, res) => {
  let result = await getHashedPassword(req.body.password);
  req.body.password01 = result;
  console.log('new passwords', req.body.password01);
  BasicUser.findByIdAndUpdate(req.params.id, req.body)
    .then(user => res.json({ msg: 'Updated successfully' }))
    .catch(err => res.status(400).json({ error: 'Unable to update the Database' }));
});
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