Home > front end >  Express async get request, calling async function hanging
Express async get request, calling async function hanging

Time:06-03

Hello I'm new to express...

I have an express file like:

const app = express();
const getPerson = require("./db/queries/PersonQuery");

app.get('/getCitizen/:id', async (req, res) => {
    try {
        const person = await getPerson.getCitizenById(`${req.params.id}`);
        console.log(person);
        res.send(person);
    } catch (e) {
        console.log(e);
    }
});

app.listen(3000);

I have the function we are calling looks like this:

const getCitizenById = async (id) => {
    try {
        const citizen = await CitizenSchema.find({
            citizenID : id
        });

        const cit1 = citizen[0];
        console.log(cit1);

        return cit1;

    } catch (e) {
        console.log(e);
    }
}

module.exports = { getCitizenById };

When I call: http://localhost:3000/getCitizen/123 On postman, my request just hangs and returns nothing, and print nothing except connecting to the database.

Can any1 help me out?

Thanks a lot

EDIT:

Citizen Schema:

const mongoose = require ('mongoose');
const Schema = mongoose.Schema;

const citizenSchema = new Schema({
    citizenID : String,
    forenames : String,
    surname : String,
    homeAddress : String,
    dateOfBirth : String,
    placeOfBirth : String,
    sex : String
}, 
    { 
        collection : 'citizen10k'
    });

module.exports = mongoose.model('citizen10k', citizenSchema);

CodePudding user response:

So I rewrote my code, I embedded the getCitizenId function into a new function that was ran as a middleware and I included next().

Now works.

  • Related