[Fixed] Timeout and unhandled promise rejection – probably caused by async

Issue

I have simple app written in node.js. I’ve added few new routes, and whole service accidentally stopped work. Console shows:

(node:22568) UnhandledPromiseRejectionWarning: MongooseError: Operation `users.find()` buffering timed out after 1
0000ms
(node:22568) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwi
ng inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(
).

My connect looks:

mongoose.connect(
    process.env.DB_CONNECTION,
    {useNewUrlParser:true},
    ()=>console.log('connected to DB')
);

My route:

router.get('/index', async function (req,res) {
    console.log(req.user);
    var usr = await User.find({});
         console.log(usr);

    console.log("cars "+usr);
    res.render('main', {user: req.user, cars:usr } )
});

I tried also async connection:

(async () => {
    try {
        await mongoose.connect(
    process.env.DB_CONNECTION,
    {useNewUrlParser:true},
    ()=>console.log('connected to DB')
    );}
catch (exc){console.log('conn error!')}
})()

And route with try catch (almost the same code like above, but surrounded by try catch block). And then service processing request very long time, and then gives GET /index - - ms - - or 500. I don’t know what’s going on.

Solution

Users goto1 and IAmDranged shows me the direction where I should to look for an answer. I wrote async connection to db and function with error handler. I will paste it below, maybe someone will use it in future. Once again thanks "goto1" and "IAmDranged" and my anonymous mate who helped me. Enjoy.

async function foo() {
    try {
    console.log("An attempt to connect");
await mongoose.connect(
    process.env.DB_CONNECTION,
    {useNewUrlParser:true},
    ()=>console.log('connected to DB')

)}catch (err){    console.log("Error during connection: "+err);
}}
foo();
mongoose.connection.on('error', err => {
    console.log("Error after connection: "+err);
});

Leave a Reply

(*) Required, Your email will not be published