Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

101
Vistas
Await function returning undefined response object

I am not much experienced with async/await, but I have incorporated the keywords in a function which basically fetch or POST data to MongoDB database. It seems like await does not wait for the promise to be fulfilled and returns an undefined response object.

I am getting the following error:

res.error(404).json({message: e.message}) ^

TypeError: Cannot read properties of undefined (reading 'error') at Object.getAllItems (/Users/myName/Desktop/TODOList/backend/Controllers/ItemsConroller.js:12:13)

Here is my code:

ItemsController.js:

const getAllItems = async (req, res) => {
    try{
        const items =  await Item.find({})
        res.status(200).json(items)
    }
    catch(e){
        res.error(404).json({message: e.message})
    }
    
}

Server.js file:

app.get('/todos', (req, res) => {
     dbItem.getAllItems().then(data => {
         console.log("entered")
         res.send(data);
     })

})

Same problem with other functions in the controller file which incorporates await/async keywords.

Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You are not passing your req and res object to your /todos endpoint: To make you app more robust try this:

You can use getAllItems as your middleware like this

app.get('/todos', dbItem.getAllItems, (req, res) => {
     if(!req.error){
         res.send(req.items)
     }else{
       res.send(req.error)
     }
})

And attach your variables to the req object and pass them to /todos

const getAllItems = async (req, res, next) => {
    try{
        const items =  await Item.find({})
        req.items = items
        next()
    }
    catch(e){
        req.error = e.message
        next()
    }
    
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda