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

179
Visualizações
While loop with asynchronous problems

I'm trying to implement a Signup back-end process where the user id is created randomly. The process checks if the user email exists. If not, it creates a random 24 character id. After this, it checks if this id already exists in other user. If not it should create the user in the database (mysql).

The functions for creating the id and to query for it in the database are:

const makeId = (length) => {
  var result = '';
  var characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  var charactersLength = characters.length;
  for (var i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
};

getUserByID = (id, callback) => {
  db.query(`SELECT userID FROM users WHERE userID=?`, [id], (err, results) => {
    if (err) {
      return callback(err, null);
    },
    return callback(null, results);
  });
};

So I called the functions this way:

let found = true;
while (found === true) {
   let userID = makeId(24);
   getUserByID(userID, (error, result) => {
      if (error) {
         return res.status(500).json({ errors: 'Database connection error' });
      }
      if (!result.length) {
         found = false;
      }
   });
}

For some reason that I am not understanding, this way is giving an infinite loop. I tried to log each of the steps, even inside the getUserByID and I think it doesn't complete this function. I suppose it's because the query is not waiting for the id (or vice-versa). I also tried a try catch method, .then().catch(){} method, async await in the functions and the async outside the while loop, but for some reason they didn't work. Any ideas of what can be wrong? Thank you.

about 4 years ago · Juan Pablo Isaza
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