Home > Software design >  returns doesn't wait for the cycle to end
returns doesn't wait for the cycle to end

Time:12-12

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.

CodePudding user response:

This is because your map function has an async function which will push the functions to the job 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
        })
    }
  • Related