等待.forEach()完成的最佳方法 [英] Best way to wait for .forEach() to complete
问题描述
有时,我需要等待.forEach()
方法完成,主要是在'loader'函数上.这就是我这样做的方式:
Sometimes I need to wait for a .forEach()
method to finish, mostly on 'loader' functions. This is the way I do that:
$q.when(array.forEach(function(item){
//iterate on something
})).then(function(){
//continue with processing
});
我忍不住觉得这不是等待.forEach()
完成的最佳方法.最好的方法是什么?
I can't help but feel that this isn't the best way to wait for a .forEach()
to finish. What is the best way to do this?
推荐答案
如果forEach
中没有异步代码,则forEach
不是异步的,例如以下代码:/p>
If there is no asynchronous code inside the forEach
, forEach
is not asynchronous, for example in this code:
array.forEach(function(item){
//iterate on something
});
alert("Foreach DONE !");
forEach
完成后,您将看到警报.
you will see the alert after forEach
finished.
否则(内部有一些异步的东西),可以将forEach
循环包装在
Otherwise (You have something asynchronous inside), you can wrap the forEach
loop in a Promise:
var bar = new Promise((resolve, reject) => {
foo.forEach((value, index, array) => {
console.log(value);
if (index === array.length -1) resolve();
});
});
bar.then(() => {
console.log('All done!');
});
信用:@ rolando-benjamin-vaz-ferreira
Credit: @rolando-benjamin-vaz-ferreira
这篇关于等待.forEach()完成的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!