使用q库在node.js中的递归函数

时间:2016-07-22 17:46:19

标签: javascript node.js recursion promise q

我需要通过从MYSQL获取数据来准备JSON。我在树结构中有MYSQl中的数据。我正在尝试使用递归函数来准备JSON以满足要求但是得到错误,我有以下两个文件

main.js

/* jshint node: true */
"use strict";

var db = require('./helpers/db');
var list_worker = require('./workers/list');
var Q = require("q");

module.exports = function (app) {
/**
 * return the profiles list
 */
app.get('/api/lists/get_list_tree_by_user/:user_id', function (req, res) {

    list_worker.fetch_list_tree(req.params.user_id, 0).done(function (out) {
        console.log(out);
        res.send(out);
    });
});
};

list.js

/* jshint node: true */
"use strict";

var db = require('../helpers/db');
var Q = require("q");
var output = {
    data: []
};

var fetch_list_tree = function (user_id, list_id) {

// prepare query to fetch lists assosiated with a user.
var query = "SELECT b.`id`, b.`name` FROM `lists_users` a JOIN `lists` b ON(a.`list_id` = b.`id`) WHERE a.`user_id` = " + user_id + " AND a.`user_role` = 'owner' AND b.`parent_id` = " + list_id + " AND b.`deleted` = 'N';";

return db.query(query).then(function (result) {

    if (result.length > 0) {
        var lists = result.map(function (list, index) {

            output.data[index] = {
                label: list.name,
                data: {
                    id: list.id
                }
            };

            return fetch_list_tree(user_id, list.id).then(function (leaf_childs) {
                output.data[index].children = [];
                output.data[index].children.push(leaf_childs);
                return leaf_childs;
            });
        });

        return Q.all(lists).then(function (data) {
            return output;
        }, function (err) {
            throw err;
        });
    } else {
        return [];
    }
}, function (err) {
    throw err;
});
};

module.exports = {
    fetch_list_tree: fetch_list_tree
};

我正在拥有的数据库中的数据     第1项         项目1.1             项目1.1.1     第2项

我想要的输出         { "label": "item 1", "data": { "id": "1" }, "children": [{ "label": "item 1.1", "data": { "id": "2" }, "children": [{ "label": "item 1.1.1", "data": { "id": "3" }, "children": [] }] }] }

我收到以下错误

TypeError: Converting circular structure to JSON

1 个答案:

答案 0 :(得分:0)

尝试将this.fetch_list_tree更改为exports.fetch_list_tree

第28行的

this != module.exports =>未定义