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.
JavaScript
x
29
29
1
async function createUser(name, email, groups) {
2
3
const grouped = [];
4
5
groups.map(async (item) => {
6
const exist = await prisma.group.findUnique({where: {id: item }})
7
if(exist) {
8
grouped.push({id: item})
9
console.log(grouped) //here is ok
10
11
} else {
12
console.log(`Group ${item} does not exist`)
13
}
14
})
15
16
console.log(grouped) //here he is []
17
18
const creating = await prisma.user.create({
19
data: {
20
name: name,
21
email: email,
22
groups: {
23
connect: grouped //here he is [], should be like [{id: 1}, {id: 2}]
24
}
25
}
26
})
27
28
}
29
Advertisement
Answer
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:
JavaScript
1
31
31
1
async function createUser(name, email, groups) {
2
3
const grouped = [];
4
5
await Promise.all(groups.map(async (item) => {
6
const exist = await prisma.group.findUnique({where: {id: item }})
7
if(exist) {
8
grouped.push({id: item})
9
console.log(grouped) //here is ok
10
11
} else {
12
console.log(`Group ${item} does not exist`)
13
}
14
})
15
)
16
17
18
console.log(grouped) //here he is []
19
20
const creating = await prisma.user.create({
21
data: {
22
name: name,
23
email: email,
24
groups: {
25
connect: grouped //here he is [], should be like [{id: 1}, {id: 2}]
26
}
27
}
28
})
29
30
}
31
notice the Promise.all()
iv’e added before the map, this extra line will wait for all the inner functions of the map.