Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!