Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

132
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda