I am trying to get the following code to work. Essentially what it does, or is supposed to is:
- Generate a random string
- Check the database if that string exists
- If it does, regenerate a string and check it again
- Once it is unique, return it
function randomString(length) {
return crypto.randomBytes(length).toString("hex");
}
const generateReferralCode = async (length) => {
logInfo('GENERATING REFERRAL CODE');
const referralCode = randomString(length);
const queryString = "SELECT * FROM referrals WHERE ReferralCode = " + mysql.escape(referralCode);
logInfo("VALIDATING UNIQUE REFERRAL CODE");
selectFromDB(queryString).then(function (returnedData) {
if (returnedData.length != 0) {
logWarning("REFERRAL CODE ALREADY EXISTS, REGENERATING...");
generateReferralCode(length);
} else {
return referralCode;
};
});
};
let generatedCode = await generateReferralCode(10);
console.log(generatedCode);
However, console.log
is always returning undefined
and not waiting for the await to finish.
I have tried a few different ways to make this work including using promises but cannot get it to properly work. I have also tried adding awaits to all calls to function but no go.