首页 > 解决方案 > 地图函数内的数组似乎接收数据,地图外它是空的

问题描述

我正在用 NodeJS 和 Express 做一个简单的 GET 和 POST 只是为了学习一些关于 PrismaJS 和 MySQL 数据库的知识。我想将分组的数组的值传递给创建函数,当我在 map 函数中使用 console.log(grouped) 时,我有我想要的值,在外面它保持空 [],当我将他传递给连接字段。

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

}

标签: javascriptnode.jsarraysexpressprisma

解决方案


问题在于async (item) => { ...我的意思是函数的map功能......你应该等待所有地图内部函数完成所以只需将你的代码更改为以下内容:

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

}

注意Promise.all()地图之前添加的iv'e,这条额外的行将等待地图的所有内部功能。


推荐阅读