【问题标题】:Array inside an map function seems to receive data, outside the map it was empty地图函数内的数组似乎接收数据,地图外它是空的
【发布时间】:2021-11-22 00:28:02
【问题描述】:

我正在用 NodeJS 和 Express 做一个简单的 GET 和 POST,只是为了学习一点关于 PrismaJS 和 MySQL 数据库的知识。我想将数组 grouped 的值传递给创建函数,当我在 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}]
      }
    }
  })

}

【问题讨论】:

  • 如果我的回答解决了您的问题 - 请批准 :)

标签: javascript node.js arrays express prisma


【解决方案1】:

问题出在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,这条额外的行将等待所有地图的内部函数。

【讨论】:

  • 谢谢,它确实有效。我还在学习如何使用 JavaScript 编写代码,所以关于基本概念还有很多内容需要介绍。
猜你喜欢
  • 2020-01-22
  • 1970-01-01
  • 2023-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-28
  • 1970-01-01
相关资源
最近更新 更多