javascript 下划线 _.each 完成后回调?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18831655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Underscore _.each callback when finished?
提问by Johnston
Is there a callback for when underscore is finished it's _.each
loop because if I console log
immediately afterwards obviously the array I am populating with the each loop is not available. This is from a nested _.each
loop.
是否有下划线完成时的回调,它是_.each
循环,因为如果我console log
紧随其后,显然我用每个循环填充的数组不可用。这是来自嵌套_.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.
回答by jrthib
The each
function in UnderscoreJS is synchronous which wouldn't require a callback when it is finished. One it's done executing the commands immediately following the loop will execute.
each
UnderscoreJS 中的函数是同步的,完成后不需要回调。一个完成后立即执行循环将执行的命令。
If you are performing async operations in your loop, I would recommend using a library that supports async operations within the each function. One possibility is by using AsyncJS.
如果您在循环中执行异步操作,我建议您使用支持每个函数中的异步操作的库。一种可能性是使用AsyncJS。
Here is your loop translated to 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");
}
});
回答by ehed
Another option is to build your callback function into the each loop on the last execution:
另一种选择是在最后一次执行时将回调函数构建到每个循环中:
_.each(collection, function(model) {
if(model.collection.indexOf(model) + 1 == collection.length) {
// Callback goes here
}
});
Edit to add:
编辑添加:
I don't know what your input/output data looks like but you might consider using _.map
instead, if you're just transforming / rearranging the contents
我不知道您的输入/输出数据是什么样的,但_.map
如果您只是转换/重新排列内容,您可能会考虑使用它