I'm making a simple GET and POST with NodeJS and Express just for learning a little about PrismaJS with MySQL database. I want to pass the value of the array grouped to the creating function, when I use console.log(grouped) inside the map function I have the values I want, outside it keeps empty [], also when I'm passing him to connect field.
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}]
}
}
})
}
CodePudding user response:
the problem is with the async (item) => { ...
I mean the function of the map
function ... you should wait for all the map inner function to finish so just change your code to the following:
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}]
}
}
})
}
notice the Promise.all()
iv'e added before the map, this extra line will wait for all the inner functions of the map.