I have the following syntax:
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
});
console.log(`[MONGODB CONNECTED]: ${conn.connection.host}`.cyan.underline);
} catch (error) {
console.error(`[ERROR]: ${error.message}`.red.underline.bold);
process.exit(1);
}
};
and I've used it like this:
await connectDB(); console.log("print after connection");
it actually works, I thought I could use await keyword only inside an async
function, however, no error is being thrown, and the database actually connects before printing the test message. Is this a legal code or I am misunderstanding something?