在for循环内的一行中运行两个或多个异步操作的最佳方式



我有以下方法,该方法循环遍历对象列表,对于每个节点,您需要执行promise。在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。将上述转换为可观测值将变成低于的情况

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, ...])加入这个阵列

我们使用pipetap算子在所有可观察器完成后将加载设置为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;
})
}   

根据这个答案。