使用 Typeorm 查询的 forEach 中不允许使用异步函数

Hug*_*ohm 1 foreach async.js typeorm nestjs

我正在尝试根据对象的元素执行 Typeorm 查询,但我对forEach和 异步函数有疑问。

我读过很多类似的问题,但没有人按预期为我工作。

这是我的代码片段,其中不允许等待forEach

public async runBudgetLimit(): Promise<void> {
        const contracts: ContractEntity[] = await this.contractService.getAllProjects();

        contracts.forEach((contract) => {
            const project: UserEntity = await this.userService.findOne(contract.milestoneId);
            const date: string = Time.moment().format('YYYY-MM-DD');
            const budgetUsed = this.trackService.getBillingByProject(project.contractId, date, '1000', '1000', true);
        });
    }
Run Code Online (Sandbox Code Playgroud)

这是异步 Typeorm 查询:

async findOne(id: string): Promise<UserEntity | undefined> {
        return this.userRepository.findOne(id);
}
Run Code Online (Sandbox Code Playgroud)

我不知道解决这个问题的最佳解决方案是什么,我不认为 for 循环是一个好的解决方案,但我对所有解决方案持开放态度。

小智 6

你可以for-of像这样使用循环:

for (const contract of contracts) {
            const project: UserEntity = await this.userService.findOne(contract.milestoneId);
            const date: string = Time.moment().format('YYYY-MM-DD');
            const budgetUsed = this.trackService.getBillingByProject(project.contractId, date, '1000', '1000', true);
        }
Run Code Online (Sandbox Code Playgroud)

或者稍微优化一下 -检查此答案for-of以了解和Promise.all方法之间的差异:

await Promise.all(contracts.map(async contract => {
            const project: UserEntity = await this.userService.findOne(contract.milestoneId);
            const date: string = Time.moment().format('YYYY-MM-DD');
            const budgetUsed = this.trackService.getBillingByProject(project.contractId, date, '1000', '1000', true);
        }));
Run Code Online (Sandbox Code Playgroud)

请记住,这些解决方案在某些情况下并不是最佳的,因为通过获取每个合约的 UserEntity ,会对数据库 AKA 进行额外的查询N+1 query problem要解决此问题,您可以使用关系加载所有用户以及合同

我不确定你为什么contractId从该项目中获得,它在对象上不可用吗contract

另外,如果回应getBillingByProject是一个承诺,你应该放在await前面