javascript - 地图函数内的数组似乎接收数据,地图外它是空的
问题描述
我正在用 NodeJS 和 Express 做一个简单的 GET 和 POST 只是为了学习一些关于 PrismaJS 和 MySQL 数据库的知识。我想将分组的数组的值传递给创建函数,当我在 map 函数中使用 console.log(grouped) 时,我有我想要的值,在外面它保持空 [],当我将他传递给连接字段。
async function createUser(name, email, groups) {
const grouped = [];
groups.map(async (item) => {
const exist = await prisma.group.findUnique({where: {id: item }})
if(exist) {
grouped.push({id: item})
console.log(grouped) //here is ok
} else {
console.log(`Group ${item} does not exist`)
}
})
console.log(grouped) //here he is []
const creating = await prisma.user.create({
data: {
name: name,
email: email,
groups: {
connect: grouped //here he is [], should be like [{id: 1}, {id: 2}]
}
}
})
}
解决方案
问题在于async (item) => { ...
我的意思是函数的map
功能......你应该等待所有地图内部函数完成所以只需将你的代码更改为以下内容:
async function createUser(name, email, groups) {
const grouped = [];
await Promise.all(groups.map(async (item) => {
const exist = await prisma.group.findUnique({where: {id: item }})
if(exist) {
grouped.push({id: item})
console.log(grouped) //here is ok
} else {
console.log(`Group ${item} does not exist`)
}
})
)
console.log(grouped) //here he is []
const creating = await prisma.user.create({
data: {
name: name,
email: email,
groups: {
connect: grouped //here he is [], should be like [{id: 1}, {id: 2}]
}
}
})
}
注意Promise.all()
地图之前添加的iv'e,这条额外的行将等待地图的所有内部功能。
推荐阅读
- python-3.x - 将 if 和 else 应用于数据框是否为空 pandas 的条件
- load-balancing - Flink 设置:将 Web UI 放在路径下
- angular - iPhone 11 Pro Max 上的问题屏幕离子应用程序
- php - F写入新行
- python - 在 Pytorch 中加载权重时的一些问题
- amazon-s3 - 使用 AWS CLI 下载共享 S3 对象
- python - 无法使用 subprocess.call 按顺序运行两个或更多命令
- arrays - 2D和3D数组有什么区别
- java - 如何在 JavaFX 中将父元素的全高设置为文本区域?
- erlang - erlang中的CAN套接字