0

im having issues with return in my function, i got two functions, the first one creates a random series of letters and numbers and the other one puts a few combinations together into a key and checks the database for it (to check if it already exists and if it does then it tries again), at the end of the second function im returning the key value as im trying to use it in my post request code. here is the code:

function keyGen(length) {
    var result           = '';
    var characters       = '0123ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789456789';
    var charactersLength = characters.length;
    for ( var i = 0; i < length; i++ ) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
   }
   return result;
}

function makeKey(company) {
    var gen1 = keyGen(6);
    var gen2 = keyGen(4);
    var gen3 = keyGen(6);

    var key = `${company}-${gen1}-${gen2}-${gen3}`;
    var rawKey = `${gen1}-${gen2}-${gen3}`;
    con.query('SELECT * FROM lkeys WHERE chars = ?', [rawKey], function(err, rows, fields) {
        console.log("here")
        if (err) throw err
        if (rows.length > 0) {
            makeKey(company)
        }
        else {
            console.log("here2")
            console.log(key)
            return key;
        }
    })
}

this is how i try to use the value from the function:

let lkey = makeKey(company);

out put for lkey is undefined

any help would be appreciated, thank you.

  • 1
    You're returning from the asynchronous callback function of `con.query()`, you're not returning from `makeKey()`. – Barmar Jun 06 '22 at 16:56
  • In `makeKey()`, there's a return from the function passed to the query, but not a return from the function. The way to get a value from a function that uses an async callback is to give that function its own callback. – danh Jun 06 '22 at 16:57

0 Answers0