如何解决在 for 循环中连续运行两个或多个异步操作的最佳方法
我有以下方法循环遍历对象列表,并为每个节点执行一个承诺。在 for 循环中连续执行两个或多个异步操作的最佳方法是什么?
async cargarEstadosPools() {
let that = this;
let nodo: Nodo;
for (var i = 0; i < that.aplicacionEntorno.entorno.nodos.length; i++) {
this.appService.loading = true;
nodo = that.aplicacionEntorno.entorno.nodos[i];
await that.obtenerDatos.Metodo(this.ruta + 'api/nodo' + '/' + aplicacionId)
.then((res: any) => {
if (res != 'Started' && res != 'Stopped') {
nodo.errorPool = res;
nodo.estadoPool = 'Error';
}
else {
nodo.errorPool = '';
nodo.estadoPool = res;
}
nodo.ejecutandoAccionNodo = false;
that.appService.loading = false;
})
}
}
解决方法
由于您使用的是 angular,因此您可以考虑使用 observable。将上面的转换为 observables 会变成下面这样
import { from,forkJoin } from 'rxjs';
import { tap } from 'rxjs/operators';
...
cargarEstadosPools() {
this.appService.loading = true;
return forkJoin(
aplicacionEntorno.entorno.nodos.map(nodo =>
from(obtenerDatos.Metodo(this.ruta + 'api/nodo' + '/' + aplicacionId))
)
).pipe(
tap(() => this.appService.loading = false)
)
}
我们正在使用代码创建一个可观察的数组
aplicacionEntorno.entorno.nodos.map(nodo =>
from(obtenerDatos.Metodo(this.ruta + 'api/nodo' + '/' + aplicacionId))
)
然后我们用 forkJoin([observable1,obsevable2,...])
我们使用 pipe
和 tap
运算符在所有 observable 完成后将加载设置为 false
要在 for 循环中并行执行异步函数,您应该执行以下操作:
await Promise.all(that.aplicacionEntorno.entorno.nodos.map(nodo => {
await that.obtenerDatos.Metodo(this.ruta + 'api/nodo' + '/' + aplicacionId)
.then((res: any) => {
if (res != 'Started' && res != 'Stopped') {
nodo.errorPool = res;
nodo.estadoPool = 'Error';
}
else {
nodo.errorPool = '';
nodo.estadoPool = res;
}
nodo.ejecutandoAccionNodo = false;
that.appService.loading = false;
})
}
来自this answer。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。