0

So, I'm new trying to understand how async functions work. Doing it with "Resolve, Reject" from Promises, works fine. But when I try to apply it with async instead of new Promise, for some reason, the function returns undefined. 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
     })
2
  • 2
    obtenerCategoria doesn't return anything, neither does crearClase Commented Oct 2, 2019 at 9:18
  • return Categoria.findOne(...) Commented Oct 2, 2019 at 9:19

2 Answers 2

2

You don't need to use callback function when you use async/await

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

obtenerCategoria doesn't have a return value. Additionally, you can use await on the Categoria.findOne() call and use try / catch instead of the call to exec(), something like this example.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.