Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

99
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!