首页 > 解决方案 > 列表请求不起作用(带有 Typescript 的 Node.js 中的 Mongoose)

问题描述

我在带有打字稿的Nodejs中使用猫鼬。在列表请求中,我有以下代码:

async list(req: Request, res: Response, next: NextFunction)
{
    try {
        let list: ListInterface[] = []
        await RequestModel.find().then(requests =>
        {
            requests.map(async request =>
            {
                const client = await Client.findById(request.cliente)
                const seller = await Seller.findById(request.vendedor)
                const company = await Company.findById(request.representada)
                const tmp =
                {
                    id: request._id,
                    data: request.data,
                    cliente: String(client?.nome_fantasia),
                    vendedor: String(seller?.nome),
                    representada: String(company?.nome_fantasia),
                    tipo: request.tipo,
                    status: request.status
                }
                list.push(tmp)
                console.log(tmp)
            })
        })
        console.log(list)
        return res.json(list)
    } catch (error) {
        next(error)
    }
}

当我在 Insomnia 中提出请求时,我收到一个空数组(在终端中 - 因为console.log(list)- 以及在 Insomnia 的预览中)[]:。在终端中,作为console.log(tmp)命令的结果,我收到了正确的数据。

我已经尝试将列表声明为类似const list = request.map(...),但它[Promise<Pending>, Promise<Pending>]在终端和[{}, {}]Insomnia 中给了我。我无法重复该测试的完全相同的代码,但我记得那些结果。

我什至不确定我在滥用哪种技术。有人可以帮我解决这个问题吗?

标签: node.jstypescriptmongoose

解决方案


.map函数返回一个 Promise 列表,所以在发回响应之前必须等待它们。

async list(req: Request, res: Response, next: NextFunction)
{
    try {
        let list: ListInterface[] = []
        const requests = await RequestModel.find()
        
        // collect all promises from the loop
        const promises = requests.map(async request =>
        {
            const client = await Client.findById(request.cliente)
            const seller = await Seller.findById(request.vendedor)
            const company = await Company.findById(request.representada)
            const tmp =
            {
                id: request._id,
                data: request.data,
                cliente: String(client?.nome_fantasia),
                vendedor: String(seller?.nome),
                representada: String(company?.nome_fantasia),
                tipo: request.tipo,
                status: request.status
            }
            list.push(tmp)
            console.log(tmp)
        })
        
        // wait for all promises to complete
        await Promise.all(promises)
        
        console.log(list)
        return res.json(list)
    } catch (error) {
        next(error)
    }
}


推荐阅读