What is the difference between querying a database and requesting an endpoint?

Viewed 45

Lately I'm trying to learn mongoose but I encountered a code and it confused me.

Why we write async keyword at the beginning of the callback function while we're querying a database? Is it already an asynchronous because of the callback function?

router.get('/', async (req, res) => {
try {
    const subscriber = await Subscriber.find()
} catch (error) {
    res.status(500).json({msg: error.message})
}})

And even if it is the way of doing this why don't we also follow the same pattern and put async keyword at the beginning of the callback function in this basic route handling?

router.get('/', (req, res) => {res.send('Hello from homepage')})
1 Answers

You have to write async keyword at the beginning of the callback because of the await keyword inside of it. Async/await is a feature that let you turn a synchronous function into an asynchronous one (not only javascript has this construct, but also others programming languages). Async/await is syntactic sugar on top of promises and makes asynchronous code easier to write and read. You can find an exhaustive explanation here.

Related