0

I have a MySQL database with the table id which stores all the unique id's generated till date, using nanoid module. I have implemented the following code to generate a unique id which is not in the table.

//sql library
const mysql = require('mysql');
const sql_obj = require(__dirname + '/../secret/mysql.json');


//nanoid library
const { customAlphabet } = require('nanoid');
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const nanoid = customAlphabet(alphabet, 30);

function uniqueid(){
    let found = 0;
    let conn = mysql.createConnection(sql_obj);
    while (found === 0){
        let id = nanoid();
        conn.connect(function(err){
            if (err){
                found = 2;
            }
            else{
                conn.query("SELECT * FROM id WHERE value = " + mysql.escape(id),function(err,result,fields){
                    if (err){
                        found = 2;
                    }
                    else{
                        if (result.length === 0){
                            found = 1;
                        }
                    }
                })
            }
        })
    }
    if (found === 2){
        return {error: 1,ret: null};
    }
    else if (found === 1){
        return {error: 0,ret: id};
    }
}

console.log(uniqueid());

I knew, my implementation is wrong. Because callbacks are asynchronous in nature, the while loop never ends and hence I got the error JavaScript heap out of memory.
I went through many articles in the web to sort this out, but couldn't. The main problem is that the function uniqueid should return some value, because, I am calling it from other JavaScript file.
Thanks for any help

1 Answer 1

1

I think best way to prevent this is using async/await.

I promisified your mySql connection. And you can send your query and values to the function.

    //sql library
    const mysql = require('mysql');
    const sql_obj = require(__dirname + '/../secret/mysql.json');


    //nanoid library
    const { customAlphabet } = require('nanoid');
    const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const nanoid = customAlphabet(alphabet, 30);

    let db = (query, values = null) => {  
        return new Promise((resolve, reject) => {
            let conn = mysql.createConnection(sql_obj);
            conn.connect(function (err) {
                if (err) {
                    reject(err);
                }
                else {
                    conn.query(query + values, function (err, result, fields) {
                        if (err) {
                            reject(err);
                            return;
                        }
                        else {
                            if (result.length === 0) {
                                resolve();
                            }
                        }
                    })
                }
            })
        })
    }

    async function uniqueid() {
        while (found === 0) {
            let id = nanoid();
            try {
                await db("SELECT * FROM id WHERE value =", mysql.escape(id));
                return { error: 0, ret: id };

            } catch (error) {
                return { error: 1, ret: null };
            }
        }
    }

    console.log(uniqueid());


Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.