Skip to content
Advertisement

Array inside an map function seems to receive data, outside the map it was empty

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}]
      }
    }
  })

}

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:

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement