[英]Javascript how to run some code after a forEach completes executing
So I want to turn my "loading" gif on and off with ng-show
. 所以我想用
ng-show
打开和关闭我的“加载” gif。 I would specifically like to turn it off after my script is done loading the array through a forEach
. 我特别想在脚本通过
forEach
完成数组加载后将其关闭。
How do I run code when the forEach
completes its entire cycle". Something similar to a .then()
, but for for
loops 在
forEach
完成整个周期后,我该如何运行代码。”类似于.then()
,但是for
循环
function selectAll(bool) {
vm.selectAllSpinner = true;
vm.practicesLeftCol = [];
if(bool === true){
vm.practices.forEach(function(practice){
practice.selected = true;
vm.practicesLeftCol.push(practice)
})
I want this after the foreach ->vm.selectAllSpinner = false;
} else if (bool === false){
vm.practices.forEach(function(practice){
practice.selected = false;
vm.practicesLeftCol = [];
})
I want this after the foreach ->vm.selectAllSpinner = false;
}
So forEach
isn't asynchronous. 因此
forEach
不是异步的。 As such, you could literally just write: 这样,您可以直接写:
function selectAll(bool) {
vm.selectAllSpinner = true;
vm.practicesLeftCol = [];
if(bool === true){
vm.practices.forEach(function(practice){
practice.selected = true;
vm.practicesLeftCol.push(practice)
})
} else if (bool === false){
vm.practices.forEach(function(practice){
practice.selected = false;
vm.practicesLeftCol = [];
})
}
vm.selectAllSpinner = false;
}
Having said that, I think the code could be cleaned up in general to be more like so: 话虽如此,我认为代码通常可以清理得更像这样:
function selectAll(bool) {
vm.selectAllSpinner = true;
vm.practicesLeftCol = [];
if (bool) {
vm.practicesLeftCol = vm.practices.reduce(function(memo, practice) {
practice.selected = true;
memo.push(practice);
return memo;
}, []);
}
vm.selectAllSpinner = false;
}
Again, neither reduce
nor forEach
are asynchronous, so this should just kinda work... 同样,
reduce
和forEach
都不是异步的,因此这应该可以工作...
In Javascript, use the semicolon ( ;
) delimiter, optionally followed by a newline, to append a command to a previous command. 在Javascript中,使用分号(
;
)分隔符(可选后跟换行符)将命令附加到上一个命令。 Thus 从而
function selectAll(bool) {
vm.selectAllSpinner = true;
vm.practicesLeftCol = [];
if(bool === true){
vm.practices.forEach(function(practice){
practice.selected = true;
vm.practicesLeftCol.push(practice)
});
vm.selectAllSpinner = false; //<---
} else if (bool === false) {
vm.practices.forEach(function(practice){
practice.selected = false;
vm.practicesLeftCol = [];
});
vm.selectAllSpinner = false; //<---
}
}
Unfortunately forEach does not have a callback - but you could do something like this: 不幸的是,forEach没有回调-但您可以执行以下操作:
if(bool === true){
vm.practices.forEach(function(practice){
practice.selected = true;
vm.practicesLeftCol.push(practice);
items++;
if(items === your_array.length) {
vm.selectAllSpinner = false;
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.