简体   繁体   English

异步 function 在 NodeJS 中返回未定义

[英]Async function returning undefined in NodeJS

So, I'm new trying to understand how async functions work.所以,我是新手,试图了解异步函数是如何工作的。 Doing it with "Resolve, Reject" from Promises, works fine.使用 Promises 中的“解决,拒绝”来做这件事,效果很好。 But when I try to apply it with async instead of new Promise, for some reason, the function returns undefined.但是当我尝试使用异步而不是新的 Promise 应用它时,由于某种原因,function 返回未定义。 Here is my code:)这是我的代码:)

note: Sorry for my english, not fluent speaker:)注意:对不起我的英语,不是流利的演讲者:)


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

You don't need to use callback function when you use async/await使用async/await时不需要使用callback function

Try this code:试试这个代码:

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 doesn't have a return value. obtenerCategoria 没有返回值。 Additionally, you can use await on the Categoria.findOne() call and use try / catch instead of the call to exec(), something like this example.此外,您可以在 Categoria.findOne() 调用上使用 await 并使用 try/catch 而不是对 exec() 的调用,类似于示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM