Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!