Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

129
Visualizações
regresa no espera a que termine el ciclo

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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 }) }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda