Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

119
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda