Home > Mobile >  How to pass response back up MVC when receiving undefined
How to pass response back up MVC when receiving undefined

Time:09-29

I'm trying to pass something down from app to controller and then model and then pass it back up, I'm moving down the chain fine into models and getting what I want to send back up, but then my controller is returning undefined. I'm aware I'm not returning the promise properly but can't quite see why I'm not returning.

Controller.js

const { fetchOwnerById } = require('./models')

const handleGreeting = (request, response) => {
    response.status(200).send({ message : 'hello from my api'})
}

const getOwnerById = (request, response) => {
    const ownerId = request.params['id'];
        fetchOwnerById(ownerId)
        .then((owner) => {
            console.log(owner)
            response.status(200).send({owner : owner})
        })
    }


module.exports = { handleGreeting, getOwnerById }

models.js

const fs = require('fs/promises')

const fetchOwnerById = (ownerId) => {
    console.log(ownerId)
    fs.readFile(__dirname   `/data/owners/${ownerId}.json`, 'utf-8').then((data) => {
        console.log(data)
        return data
        // response.status(200).send(data)
        })
}

module.exports = { fetchOwnerById }

I'm receiving TypeError: Cannot read properties of undefined (reading 'then')

CodePudding user response:

The fetchOwnerById method doesn't return anything, so it returns undefined, you need to return a promise of data so you can call then.

const fs = require('fs/promises')

const fetchOwnerById = async (ownerId) => {
    console.log(ownerId)
    return await fs.readFile(__dirname   `/data/owners/${ownerId}.json`, 'utf-8')
}

module.exports = { fetchOwnerById }

  • Related