0

I am trying to get the following code to work. Essentially what it does, or is supposed to is:

  1. Generate a random string
  2. Check the database if that string exists
  3. If it does, regenerate a string and check it again
  4. 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.

alphadmon
  • 396
  • 4
  • 17
  • 1
    Does this answer your question? [Get undefined result while await recursive function](/q/58621354/90527) – outis Oct 10 '22 at 22:19
  • 3
    `randomString()` is not asynchronous so does not need `await` – Phil Oct 10 '22 at 22:20
  • Thank you both. Yes, @Phil, I saw that, a mistake on my part as I had been experimenting with different configurations and forgot to remove that await. Thanks for pointing it out. – alphadmon Oct 10 '22 at 22:28

1 Answers1

2

You forgot to actually use await

function randomString(length) {
  return crypto.randomBytes(length).toString("hex");
}

const generateReferralCode = async (length) => {
  logInfo('GENERATING REFERRAL CODE');
  const referralCode = await randomString(length);
  const queryString = "SELECT * FROM referrals WHERE ReferralCode = " + mysql.escape(referralCode);

  logInfo("VALIDATING UNIQUE REFERRAL CODE");
  const returnedData = await selectFromDB(queryString)
  if (returnedData.length != 0) {
    logWarning("REFERRAL CODE ALREADY EXISTS, REGENERATING...");
    return generateReferralCode(length);
  } else {
    return referralCode;
  };
};

let generatedCode = await generateReferralCode(10);
console.log(generatedCode);
Konrad
  • 21,590
  • 4
  • 28
  • 64