【问题标题】:returns doesn't wait for the cycle to endReturns 不等待循环结束
【发布时间】:2022-01-16 03:39:49
【问题描述】:

我的代码(打字稿)有问题:

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

这个函数需要返回 2 个数组,但是第二个数组(bot)总是空的。
这是因为 return 在循环之前执行。
循环完成后如何执行返回?

在此先感谢,抱歉英语不好。

【问题讨论】:

  • 你有点滥用map,因为你忽略了返回值。但是您需要返回值才能等待异步函数返回的 Promises。

标签: javascript arrays loops return


【解决方案1】:

这是因为您的 map 函数有一个 async 函数,该函数会将函数推送到 microtask queue 并在 call stack 为空时执行。

为了能够返回 bot 数组,您需要等待这些异步函数完成。

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

【讨论】:

    猜你喜欢
    • 2021-11-20
    • 2021-03-02
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    相关资源
    最近更新 更多