I am trying to create a function that would generate 4 unique id (hexadecimal) to insert into my database. I put the query inside a do while loop to check for collision, if the code is already present, I regenerate the code, if not, I return the value.
The problem is that the loop exits before intended. For example if the code 'a' is generated but already presented in the database, the code gets regenerated but the loop exits and a new query never gets made. The new code does not get returned - instead the first code that was generated is returned.
Here's my code:
const FIND_EXISITNG_COURT =
"SELECT access_code,team1,team2 FROM courts WHERE access_code= ?";
function generateAccessCode() {
var random = Math.floor(Math.random() * (+30 - +0)) + +0;
var code = random.toString(16);
var hasDupe = false;
do {
connection.query(FIND_EXISITNG_COURT, [code], (err, results) => {
if (err) {
throw err;
} else if (results.length > 0) {
random = Math.floor(Math.random() * (+30 - +0)) + +0;
code = random.toString(16);
hasDupe = true;
} else {
hasDupe = false;
}
});
} while (hasDupe);
return code;
}
I am new to NodeJS so I don't know if it's bad practice to do this. Any help would be much appreciated!