node.js - 使用节点JS和数据库(mysql / mongoDB)生成嵌套数组,使用递归
问题描述
我正在尝试使用 nodeJS 生成嵌套数组。我也尝试过使用 mongoDB 和 MYSQL。
我的数据库结构:
parent_id | left_id | right_id
我尝试在 PHP 中执行此操作,并且成功了。我在 nodeJS 中编写了相同的逻辑,但它不起作用。我的猜测是这不起作用,因为 nodeJS 是异步的。
代码:
function testRecX(parent_id, callback) {
let xyz = {};
connection.query('SELECT * FROM test WHERE parent_id = ' + parent_id, function (err, rows, fields) {
if (err) throw err
xyz.parent = parent_id;
if(rows[0].left_id) {
console.log(" -- LEFT -- " + rows[0].left_id);
xyz.left = testRecX(rows[0].left_id, null);
}
if(rows[0].right_id) {
console.log(" -- RIGHT -- " + rows[0].right_id);
xyz.right = testRecX(rows[0].right_id, null);
}
if(callback == null) {
console.log(" -- RETURN -- " + xyz);
return xyz;
}
else {
console.log(" -- CALLBACK -- " + xyz);
return callback(xyz);
}
});
}
我得到的输出:
需要输出:
{
parent: 1,
left: {
parent: 2,
left: {
parent: 4,
left: {
parent: 8,
left: null,
right: null
},
right: null
},
right: {
parent: 5,
left: null,
right: null
}
},
right: {
parent: 3,
left: {
parent: 6,
left: null,
right: {
parent: 9,
left: null,
right: null
}
},
right: {
parent: 7,
left: null,
right: null
}
}
}
解决方案
这是因为 Node.js 是非渲染阻塞的。它不会等待SELECT
查询完成。因此,对于 I/O 操作,请使用 promise。您的代码应变为:
function testRecX(parent_id, callback) {
let xyz = {};
connection.query('SELECT * FROM test WHERE parent_id = ' + parent_id,
function (err, rows, fields).then(rows=>{
//your other code here
}).catch(err=>console.log(err))
推荐阅读
- python - 转置列表 - Python
- reactjs - React - 将 cookie 发送到 Express
- amazon-web-services - 尝试在 ECS 上的 CI/CD 管道中执行 Blue Green Deploy 时卡在 Code Deploy
- jmeter - JMeter HTML 报告:显示所有失败的交易都在 HTML 报告中传递
- java - 如何通过 Java/Kotlin API 从 KeyCloak 请求 JWT 令牌
- excel - 复制数据并重新排序列并粘贴到另一个工作簿
- openedge - 想要在任何数据字段中搜索所有包含“kan”的客户
- php - 如何在 PHP 中删除对象数组
- datatable - 动态启用数据表中的排序
- python - Pythin gi 模块和 OSX Catalina 之间是否存在冲突?