2016-09-14 73 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