递归、回调和nodejs

recursion, callback and nodejs

我在递归、回调和 nodejs 方面遇到了很大的问题。

我有这个对象,例如:

var a= [
    {index : 1},
    {index : 2},
    {index : [
        {index : 11},
        {index : 12},
        {index : [
            {index : 111},
            {index : 112},
            {index : "end-of-tree"},
        ]},
    ]},
    {index : 4},
]

我想按顺序显示:

1
2
11
12
111
112
end-of-tree
4

与 console.log(值)

在纯 javascript 中很简单,但作为异步节点 运行,它有点复杂。

谁能帮帮我?

我设法让它工作。

JSON 例子:

var a= [
    {index : 1},
    {index : 2},
    {index : [
        {index : 11},
        {index : 12},
        {index : [
            {index : 111},
            {index : 112},
            {index : "end-of-tree 1xx"},
        ]},
    ]},
    {index : 4},
    {index : [
        {index : 51},
        {index : 52},
        {index : [
            {index : 531},
            {index : 532},
            {index : [
                {index : 5341},
                {index : 5342},
                {index : [
                    {index : 53441},
                    {index : 53442},
                    {index : "end-of-tree 5xx"},
                ]}, 
            ]},
        ]},
    ]},
    {index : 6},
    {index : 7},
    {index : 8},
    {index : 9},    
    {index : [
        {index : 'A0'},
        {index : 'A1'},
        {index : [
            {index : 'A21'},
            {index : 'A22'},
            {index : [
                {index : 'A311'},
                {index : 'A312'},
                {index : [
                    {index : 'A3131'},
                    {index : 'A3132'},
                    {index : "end-of-tree Axx"},
                ]}, 
            ]},
        ]},
    ]}, 
]

Javascript代码:

function tree(json) {
    item=json[0];
    if (item) {
        if (Array.isArray(item.index)) {
            tree(item.index);
        } else {
            console.log(item.index)
            json.shift();
            if (json) tree(json);
        }       
    } else {
        a.shift();
        if (a.length>0) tree(a);
    }
} 

tree(a)

控制台日志结果:

1
2
11
12
111
112
end-of-tree 1xx
4
51
52
531
532
5341
5342
53441
53442
end-of-tree 5xx
6
7
8
9
A0
A1
A21
A22
A311
A312
A3131
A3132
end-of-tree Axx

您可以尝试像这样更简单的方法!

function ff(item){
  var temp = item.index;
  if(temp instanceof Array) temp.forEach(ff);
  else console.log(temp);   
}
a.forEach(ff);

事实上你的问题没有任何异步,它是数组中的同步迭代!

@alex-rocabillis.... https://github.com/oracle/node-oracledb/blob/master/doc/api.md#-523-execute

oracle 执行函数是异步的。 我要创建另一个 post 来解释这个问题。

5.2.3 执行()

原型

void execute(String sql, [Object bindParams, [Object options,]] function(Error error, [Object result]){}); Return价值

None

描述

此调用执行 SQL 或 PL/SQL 语句。有关示例,请参阅 SQL 执行。

这是一个异步调用。

要执行的语句可能包含 IN 绑定、OUT 或 IN OUT 绑定值或变量,它们使用对象或数组进行绑定。

一个回调函数returns一个结果对象,包含任何获取的行、任何 OUT 和 IN OUT 绑定变量的值,以及受 DML 语句执行影响的行数。

参数