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 (!
This is basically the same code, but with callbacks plus some asynchronous flow control code. Of course, you can use the async package.
source share