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

137
Visualizações
returns doesn't wait for the cycle to end

I've a problem with my code (typescript):

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
        })
    }

This function need to return 2 array, but the second array (bot) is always empty.
This is because return is executed before the loop.
How I can execute the return when the loop finish?

Thanks in advance and sorry for bad english.

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

0

This is because your map function has an async function which will push the functions to the microtask queue and will execute when the call stack is empty.

To be able to return the bot array you need to wait for these async functions to complete.

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