2016-07-16 188 views
0

有时我需要等待.forEach()方法完成,主要是在'loader'函数上。这是我做的方式:等待.forEach()完成的最佳方式

$q.when(array.forEach(function(item){ 
    //iterate on something 
})).then(function(){ 
    //continue with processing 
}); 

我不禁觉得,这不是等待.forEach()来完成的最佳途径。做这个的最好方式是什么?

回答

3

forEach不同步,例如在此代码:

array.forEach(function(item){ 
    //iterate on something 
}); 
alert("Foreach DONE !"); 

你会看到警报forEach结束后。

0
var foo = [1,2,3,4,5,6,7,8,9,10]; 

如果你实际上做内循环异步的东西,你可以用它在一个承诺......

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!'); 
}); 
0

不,它是阻断。看看specification of the algorithm

因此,无论您在foEach()完成后,您为外部输入的代码都将执行。

array.forEach(function(item){ 
    //iterate on something 
}) 
// @TODO this code will be executed once above block is done.