2016-09-14 101 views
0

我有一个对象如何for ... in循环中async.waterfall的NodeJS

var object = { 
name : null, 
id : 12, 
sys : [{name:'sys'}], 
info : 'string', 
some : [{name:'some'}], 
end : null 
} 
在我的NodeJS需要在这个对象数组找到,然后stringfy,发送给Redis的

。所以我搜索阵列

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. 
    } 
    } 
    ]) 
} 
} 

但它是异步,所以在第二个功能object[key]是不是在以前的功能相同object[key]。例如在瀑布的第一个函数中,我把object[key] = sys写入redis,然后等待密钥,然后在第二个函数中获得密钥object[key] = name。我怎样才能把钥匙放到正确的物体上?

回答

1

我就尝试了一下不同的方法

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(); 
    }); 
}); 

更新 刚刚意识到没有理由系列的forEach应该正常工作。

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'); }); 
+0

哦,thx,我现在就试试 – YoroDiallo

+0

是的,它的工作原理,thx更新!多谢) – YoroDiallo