NodeJS noob issue with mysql and async calls

54 Views Asked by At

I'm trying to build a simple Node app consisting of two files. One (main) file contains and exports a db connection (content of file index.js):

 const con = mysql.createConnection({
    host: process.env.DBHOST,
    user: process.env.DBUSER,
    password: process.env.DBPASS,
    database: process.env.DBSCHEMA,
    charset: 'utf8mb4'
});

module.exports = {
    getDBAccess: function(sqlString, callback) {
        con.connect(function(err) {
            if (err) throw err;

            // query to the database and get the records
            con.query(sqlString, function (err, recordset) {

                if (err) return callback(err)

                return callback(null, recordset);
            });
        });
    }
}

and in another file (process.js) i need to:

  1. get data to a function
  2. split data according to a regex
  3. for each match (in loop) execute a db query to replace current value from the loop
  4. return modified text

Code that should do things 1-4 looks like this (in process.js file):

function processHashtagsFromInput(text) {
        let regex = /#([^`~!@$%^&*\#()\-+=\\|\/\.,<>?\'\":;{}\[\]* ]+)/g; //find all hashtags

        do {
            match = regex.exec(text);
            if (match) {
                const updatePromises = [];
                updatePromises.push(get_hashtag(match[1], function(hi) {
                    let syntax = '#[' + hi + ']';
                    text = text.replace(match[0], syntax);
                }));

                await Promise.all(updatePromises);
            }
        } while (match);


        return text;
    }

function get_hashtag(tag, fnc) {
    let md5_val = md5(tag);
    let hash_id = -1;

    let query = "some_SELECT_query_here_searching_for_rows_with_matching_MD5_value";
    main_file.getDBAccess(query, function (err, rows, fields) {
        if (err) throw err;

        rows.forEach(function (row) {
            hash_id = row.id; //nevermind the loop, there's one or no result anyway
        });

        fnc(hash_id);
    });
}

The problem i'm having is that despite what i apply from various StackOverflow posts, i can't make sure

return text;

is executed only after entire loop is executed. I know it has to do with default async execution of the mysql but if i'm not concerned about the speed - how can i force my code to execute sequentially (loop -> query db -> process result -> loop -> ... return)?

Thanks!

EDIT: I tried with this approach but idk how to make sure Promis ecan access outside variable called "text", that's the only problem heh

if (match) {
                
                new Promise( () => {
                    get_hashtag(match[1], function(hi) {
                        let syntax = '#[' + hi + ']';
                        text = text.replace(match[0], syntax);
                    })
                });
                
            }
1

There are 1 best solutions below

1
Azri On

your function processHashtagsFromInput(text) is missing the keyword async , async function processHashtagsFromInput(text) because you are using await without it