【问题标题】:How to handle map function creating an object [duplicate]如何处理创建对象的地图功能[重复]
【发布时间】:2022-01-21 21:16:00
【问题描述】:

我希望我的data 对象是这样的:

{ email: "x", password: "x" }

记录data给我带来:[ Promise { undefined }, Promise { <pending> } ]

我必须改变什么才能得到想要的结果?

const controller = (modelName: string, fields: string[]) => {
    const createOne = (req: Request, res: Response) => {
        wrapper(req, res, async (prisma: PrismaClient) => {
            const data = fields.map(async (field) => {
                if (field in req.body) {
                    if (field === 'password') {
                        return { [field]: await hash(req.body[field], await genSalt(10)) }
                    }
                } else {
                    return { [field]: req.body[field] }
                }
            })
            console.log(data)
            // @ts-ignore
            return await prisma[modelName].create({ data })
        })
    }
    ...
}

【问题讨论】:

  • 是的。谢谢。

标签: typescript


【解决方案1】:

fields.map(async (field) => {/* ... */}) 将返回一组承诺。您可以使用 Promise.all 在一个 Promise 中等待所有值:

const mappedValues = await Promise.all(fields.map(async (field) => {/* ... */})

【讨论】:

  • 现在在一个数组中创建了 2 个对象。我想让它们合并到一个对象中。我该怎么做?
  • const merged = Object.assign(...mappedValues)
  • 谢谢。现在它工作得很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-26
  • 2014-04-28
  • 1970-01-01
  • 2013-05-28
  • 2019-03-18
相关资源
最近更新 更多