首页 > 解决方案 > 使用节点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

解决方案


这是因为 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))

推荐阅读