簡體   English   中英

處理 promise 和異步等待 function

[英]Handling promise and async await function

我在節點中有這個 function 並表達

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

但是,我收到此錯誤

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

我建議您也將第一部分包裝在 try/catch 中。 如果req.body沒有被填充,或者如果new Playlist拋出任何類型的錯誤,因為這是一個異步 function,這將成為一個被拒絕的 Promise。 這更安全:

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

如果您收到“Cannot read property 'song' of undefined”錯誤,這意味着無法解析請求正文並保持undefined 可能發送了錯誤的content-type header 或者您沒有正確設置正文解析中間件。

您已經使用 try...catch 處理了異常,這很棒。 盡管在此try catch之外可能是一個問題。 所以這里可能有兩個錯誤

  1. req.body.songreq.body.artistPlaylist不是有效的 class
  2. 在你的 catch 塊res.status(400).json({ message: err.message })這可能是另一個問題。

如果您嘗試捕獲整個代碼塊並記錄錯誤,那就太好了,它會很清楚。

UnhandledPromiseRejectionWarning發生是因為您沒有捕獲異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM