我在Nodejs中使用mongoose和打字脚本。在列表请求中,我有以下代码:
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>]
,在失眠中给出了[{},{}]
。我不能重复这个测试完全相同的代码,但我记得那些结果。
我甚至不确定我在滥用哪种技术。有人能帮我解决这个问题吗?
.map
函数返回承诺列表,因此在发送回响应之前必须等待它们。
null
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)
}
}