簡體   English   中英

異步 function 在 NodeJS 中返回未定義

[英]Async function returning undefined in NodeJS

所以,我是新手,試圖了解異步函數是如何工作的。 使用 Promises 中的“解決,拒絕”來做這件事,效果很好。 但是當我嘗試使用異步而不是新的 Promise 應用它時,由於某種原因,function 返回未定義。 這是我的代碼:)

注意:對不起我的英語,不是流利的演講者:)


   category = body.category

   obtenerCategoria = async(category) => {
     Categoria.findOne({ descripcion: category })
       .exec((err, categoriaDB) => {
         if (err) {
           throw new Error(err)
         }
         if (!categoriaDB) {
           return res.status(400).json({
             ok: false,
             msg: 'Categoria no encontrada'
           })
         }
         console.log(categoriaDB); // Works fine here
         return categoriaDB
       })
   }


   crearClase = async() => {
     categoria = await obtenerCategoria(category);
     console.log(categoria); //getting nothing here
   }

   crearClase()
     .then()
     .catch(e => {
       return e
     })

使用async/await時不需要使用callback function

試試這個代碼:

obtenerCategoria = async(category) => {
    const categoriaDB = await Categoria.findOne({ descripcion: category });
    if (!categoriaDB) {
        return res.status(400).json({
            ok: false,
            msg: 'Categoria no encontrada'
        })
    }
    console.log(categoriaDB); // Works fine here
    return categoriaDB
}

obtenerCategoria 沒有返回值。 此外,您可以在 Categoria.findOne() 調用上使用 await 並使用 try/catch 而不是對 exec() 的調用,類似於示例。

暫無
暫無

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

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