Process recursively in Nodejs

[ { name: 'test1', fields: [ { name: 'test11', fields: [ { name: 'test111', fields: [ { name: 'test1111' } ] } ] } ] }, { name: 'test2', fields: [ { name: 'test21' }, { name: 'test22' } ] } 

]

I want to process the field name in the above array, recursively in nodejs. Loop does not work due to the asynchronous behavior of nodejs.

+6
source share
1 answer

You need to define a "process." If this is something synchronous, nothing special, obviously:

 function visit (visitor, obj) { if (Array.isArray(obj)) return obj.forEach(visit.bind(null, visitor)) if (Array.isArray(obj.fields)) obj.fields.forEach(visit.bind(null, visitor)) visitor(obj) } function visitor (obj) { console.log(obj.name) } visit(visitor, data) 

If in visitor you want something asynchronous, there are many options. Assuming you want to process the node files first (in parallel) and then the node itself:

 // the order of arguments is weird, but it allows to use `bind` function visit (visitor, callback, obj) { var array if (Array.isArray(obj)) array = obj if (Array.isArray(obj.fields)) array = obj.fields if (!array) return visitor(obj, callback) // number of pending "tasks" var pending = array.length var done = false function cb () { // ensure that callback is called only once if (done) return if (!--pending) { done = true // after all children are done process the node itself if (!Array.isArray(obj)) return visitor(obj, callback) //if the whole node is array callback() } } array.forEach(visit.bind(null, visitor, cb)) } function visitor (obj, callback) { process.nextTick(function () { console.log(obj.name) callback() }) } visit(visitor, after, data) function after () { console.log('all done') } 

This is basically the same code, but with callbacks plus some asynchronous flow control code. Of course, you can use the async package.

+1
source

All Articles