Nikssj_
Nikssj_

Reputation: 187

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

Upvotes: 0

Views: 856

Answers (2)

ItayL
ItayL

Reputation: 28

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.

Upvotes: 0

mohsen saremi
mohsen saremi

Reputation: 715

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
}

Upvotes: 2

Related Questions