2013-09-16 39 views
14

當下劃線完成時,是否有回調,因爲如果我console log之後馬上顯然我填充每個循環的數組不可用。這是來自嵌套的_.each循環。下劃線_each回調完成後?

_.each(data.recipe, function(recipeItem) { 
    var recipeMap = that.get('recipeMap'); 
    recipeMap[recipeItem.id] = { id: recipeItem.id, quantity: recipeItem.quantity }; 
}); 
console.log(that.get('recipeMap')); //not ready yet. 
+13

'_.each'是同步的。它不需要回調。循環將在你的'console.log'行到達之前完成。如果你在'_.each'內部調用異步函數*,那就是另一個問題。 – meagar

+0

'_.each'是同步的,並且只會在函數對所有項目執行後纔會返回。如果'that.get'是異步的,'each'不會幫助你。 – Bergi

回答

15

each功能UnderscoreJS是同步的,當它完成這不會需要一個回調。一個是在循環執行後立即執行命令。

如果您在循環中執行異步操作,我會建議使用支持每個函數內的異步操作的庫。一種可能性是使用AsyncJS

這裏是你的循環轉換爲AsyncJS:

async.each(data.recipe, function(recipeItem, callback) { 
    var recipeMap = that.get('recipeMap'); 
    recipeMap[recipeItem.id] = { id: recipeItem.id, quantity: recipeItem.quantity }; 
    callback(); // show that no errors happened 
}, function(err) { 
    if(err) { 
     console.log("There was an error" + err); 
    } else { 
     console.log("Loop is done"); 
    } 
}); 
+0

但是如果控制檯裏面有東西在循環,它不會被觸發 – Muhaimin

8

另一種選擇是建立你的回調函數將在最後執行的每一個循環:

_.each(collection, function(model) { 
    if(model.collection.indexOf(model) + 1 == collection.length) { 
     // Callback goes here 
    } 
}); 

編輯補充:

我不知道你的輸入/輸出數據是什麼樣的,但你可能會考慮使用_.map來代替,如果你只是轉換/重新排列內容