我在Nodejs中使用带有typescript的mongose。在列表请求中,我有以下代码:
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)
——也在Insomia的预览中(:[]
。在终端中,由于console.log(tmp)
命令,我接收到了正确的数据。
我已经尝试将列表声明为类似const list = request.map(...)
的内容,但它在终端中为[Promise<Pending>, Promise<Pending>]
,在失眠中为[{}, {}]
。我不能重复这个测试中完全相同的代码,但我记得那些结果。
我甚至不确定我在滥用哪项技术。有人能帮我解决这个问题吗?
.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)
}
}