首页 > 解决方案 > 在 NodeJS 中返回未定义的异步函数

问题描述

所以,我是新手,试图了解异步函数是如何工作的。使用 Promises 中的“解决,拒绝”来做这件事,效果很好。但是当我尝试使用 async 而不是 new Promise 应用它时,由于某种原因,该函数返回未定义。这是我的代码:)

注意:对不起我的英语,不是流利的演讲者:)


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

标签: javascriptnode.jsasynchronousasync-await

解决方案


使用时不需要使用callback函数async/await

试试这个代码:

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
}

推荐阅读