首页 > 解决方案 > mysql和异步调用的NodeJS noob问题

问题描述

我正在尝试构建一个由两个文件组成的简单 Node 应用程序。一个(主)文件包含并导出一个数据库连接(文件 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);
            });
        });
    }
}

在另一个文件(process.js)中,我需要:

  1. 获取数据到函数
  2. 根据正则表达式拆分数据
  3. 对于每个匹配项(在循环中)执行数据库查询以替换循环中的当前值
  4. 返回修改后的文本

应该执行 1-4 的代码如下所示(在 process.js 文件中):

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);
    });
}

我遇到的问题是,尽管我从各种 StackOverflow 帖子中申请,但我无法确定

return text;

仅在执行整个循环后执行。我知道这与 mysql 的默认异步执行有关,但如果我不关心速度 - 我如何强制我的代码按顺序执行(循环 -> 查询数据库 -> 处理结果 -> 循环 -> .. 。 返回)?

谢谢!

编辑: 我尝试过这种方法,但我知道如何确保 Promis 可以访问名为“text”的外部变量,这是唯一的问题,呵呵

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

标签: node.jsnode-mysqlnode-async

解决方案


function processHashtagsFromInput(text)缺少关键字async async function processHashtagsFromInput(text)因为您在await没有它的情况下使用


推荐阅读