Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!