YoroDiallo YoroDiallo - 2 months ago 22
Node.js Question

how to for...in loop in async.waterfall nodejs

I have an object

var object = {
name : null,
id : 12,
sys : [{name:'sys'}],
info : 'string',
some : [{name:'some'}],
end : null
}


in nodejs I need to find in this object arrays and then stringfy and send to redis. So I search array

for(var key in object){
if(Array.isArray(object[key])) {
async.waterfall([
function(callback) {
// put finded item to redis, then from redis I need to get the key.
},
function(res, body, callback) {
if(body) {
object[key] = body // I need to replace array > key.
}
}
])
}
}


But It's async, so in second function
object[key]
is not the same
object[key]
in previous function. For example in first function of waterfall I put
object[key]
= sys into redis, then I wait for the key, and in second function when I get the key
object[key]
= name. How can I past key to correct object?

Answer

I would try a bit different approach

var keys = [];
// get the keys that refers to array property
for(var key in object) { 
    if(Array.isArray(object[key])) keys.push(key);
}

async.forEachSeries(keys, function(key, next){
    // use object[key] 
    // Do the redis thing here and in it's callback function call next
    ........, function(){
        object[key] = body;
        next();
    });
});

Update Just realised there's no reason for series, forEach should work as well.

async.forEach(keys, function(key, next){
    // use object[key] 
    // Do the redis thing here and in it's callback function call next
    ........, function(){
        object[key] = body;
        next();
    });
}, function(err){ console.log('done'); });