URL Shortener Microservice - async functions

I’m working on the URL shortener challenge and am wondering why we need to use async/await for the middleware functions and the mongoose method calls?

Example from my code:

app.get('/api/shorturl/:shorturl', async (req, res) => {
	var path = req.params.shorturl;
	const urlSearch = await URL.findOne({ short_url: path });
	...
}

I’ve tried running my code without it and I’m trying to understand the process a little better.

The route handler has to be async if you want to use async/await inside it. You can also use .then with the Mongoose methods.

I think technically they are thenables and not promises. If the API docs for the method says it returns a Query I believe it is returning a thenable.

Docs - Queries are Not Promises


Older versions of Mongoose also supported callbacks which is the version used in the boilerplates.

But why do we need to use async? I guess I’m trying to understand if this is standard whenever working with a database.

It is if the API doesn’t use callbacks. DB interactions are not synchronous in nature.

But in general, being able to chain or await can be more ergonomic and give a nicer API to work with.

1 Like

You want to use async/await with Mongoose methods because you are working with promises.

Your code might appear to work without async/await in some cases because:

  1. The database operation might be fast enough that you don’t notice the delay
  2. The rest of your code might not depend on the database result
  3. You might not be handling errors properly

But using async/await ensures:

  1. You get the actual data before proceeding
  2. You can properly handle errors with try/catch
  3. Your code executes in the correct order
1 Like