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

175
Vistas
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 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