node.js - 列表请求不起作用(带有 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 中给了我。我无法重复该测试的完全相同的代码,但我记得那些结果。
我什至不确定我在滥用哪种技术。有人可以帮我解决这个问题吗?
解决方案
.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)
}
}
推荐阅读
- mysql - 多表连接需要几个小时,有没有更好的方法?
- c# - Dot Net Core 3.0 上的 Dapper 数据序列化问题
- python-3.x - 切片熊猫系列
- php - 从特定数字开始更改表中所有行的 id 值
- ios - 试图将来自 API 的 JSON 对象中的字符串值解析为 Int 的结构
- r - ggplot 轴类别标签中化学式的正确显示
- python - 将 matplotlib 轴更改为数据点的范围(数量)而不是数据点的长度
- versioning - 为什么 certbot “版本” 域证书文件夹
- linux - 两个 docker 容器(nginx 和一个 web 应用程序)不能一起工作(linux)
- if-statement - 从 sh 语法到 Makefile 语法的条件