Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Async/Await not waiting before running next code

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading