Tengo un problema con mi código (mecanografiado):
async getAllServers(@Res() response) { const servers = await this.serverService.getAllServers(); let bot = [] servers.map(async server => { console.log(server.id) bot.push(await this.serverService.getInfo(server.id)); console.log(bot) }) return response.status(HttpStatus.OK).json({ bot, servers }) } Esta función necesita devolver 2 matrices, pero la segunda matriz (bot) siempre está vacía.
Esto se debe a que el retorno se ejecuta antes del bucle.
¿Cómo puedo ejecutar el retorno cuando finaliza el bucle?
Gracias de antemano y perdón por el mal inglés.
Esto se debe a que su función de map tiene una función async que empujará las funciones a la microtask queue y se ejecutará cuando la call stack esté vacía.
Para poder devolver la matriz de bot , debe esperar a que se completen estas funciones asíncronas.
async getAllServers(@Res() response) { const servers = await this.serverService.getAllServers(); let bot = [] let botServerCalls = []; // get the API call Promise in an array to be able to hit them parallely botServerCalls = servers.map(server => { console.log(server.id) // assuming this returns a Promise to make API call return this.serverService.getInfo(server.id); }); // use Promise.all to make API calls in parallel and wait for Promise.all to resolve bot = await Promise.all(botServerCalls); return response.status(HttpStatus.OK).json({ bot, servers }) }