Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to handle map function creating an object

I want my data object to be like:

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

Logging data brings me: [ Promise { undefined }, Promise { <pending> } ]

What do I have to change to get the desired result?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

fields.map(async (field) => {/* ... */}) will return an array of promises. You can use Promise.all to await all of the values in one promise:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading