node.js - 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-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);
})
});
}
解决方案
您function processHashtagsFromInput(text)
缺少关键字async
,
async function processHashtagsFromInput(text)
因为您在await
没有它的情况下使用
推荐阅读
- java - Kruskal 算法 - 我在这个实现中的问题是什么?
- android - Android Project的状态栏不能变色
- python - matplotlib:如何精确定位文本?
- php - HTML/PHP:移动 Web 导航栏不起作用
- java - 在 Resteasy Reactive / Quarkus 中使用枚举作为查询参数
- python - Python 部署到 Azure 应用服务失败且没有错误
- html - Bootstrap 导航栏右对齐
- java - 从 invokedynamic 调用 Java varargs 方法
- java - RecycleView 中显示的额外空 ViewHolder 布局
- homebrew - 把 brew install openconnect 403 ,怎么安装?