Javascript 完成时 Foreach 回调
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31193371/
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
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:21:40 来源:igfitidea点击:
Foreach callback when finish
提问by Luciano Nascimento
I want to execute a callback when foreach
has finished, but it's not working properly.How can I do that?
我想在foreach
完成后执行回调,但它无法正常工作。我该怎么做?
var response = [];
myArray.forEach(function(data) {
data.asyncFunction(function(result) {
response.push(result);
});
}, function() {
console.log(response); // Not being called.
});
console.log(response); // (Empty) Executed before foreach finish.
回答by Anoop
Because forEach
accept only one callback
. Since you are calling asynchronous method inside forEach
you need to check whether all asyn call completed
因为forEach
只接受一个callback
。由于您在内部调用异步方法,因此forEach
您需要检查所有异步调用是否已完成
var response = [];
myArray.forEach(function(data, index) {
data.asyncFunction(function(result) {
response.push(result);
if(response.length === myArray.length) {
//foreach work done
}
});
});
回答by gypsyCoder
Try this :
尝试这个 :
myArray.forEach(function(element, index, array){
asynchronous(function(data){
if (index === myArray.length - 1) {
response.push(data);
functionAfterForEach();
}
})
});