Search code examples
javascriptnode.jsexpressasync-awaites6-promise

Handling promise and async await function


I have this function in node and express

router.post('/', async (req, res) => {
    const playlist = new Playlist({
        song: req.body.song,
        artist: req.body.artist
    })

    try {
        const newPlaylist = await playlist.save()
        res.status(201).json(newPlaylist)
    } catch (err) {
        res.status(400).json({ message: err.message })
    }
})

However, I am getting this error

(node:23242) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'song' of undefined

Solution

  • I'd recommend you also wrap that first part in a try/catch. If req.body somehow doesn't get populated, or if new Playlist throws any sort of error, since this is an async function, that'll become a rejected Promise. This is safer:

    router.post('/', async (req, res) => {
        try {
            const playlist = new Playlist({
                song: req.body.song,
                artist: req.body.artist
            })
            const newPlaylist = await playlist.save()
            res.status(201).json(newPlaylist)
        } catch (err) {
            res.status(400).json({ message: err.message })
        }
    })
    

    If you're getting a "Cannot read property 'song' of undefined" error, that means that the request body could not be parsed and remains undefined. Maybe the wrong content-type header was sent or you don't have a body parsing middleware set up correctly.