A coroutine is a special kind of function that can pause and resume its execution, allowing asynchronous programming.
When you call an async function, it doesn’t run immediately like a regular function.
Instead, it returns a coroutine object — essentially a “promise” that it will run when awaited.
Coroutine object in practice
asyncdefsay_hello():print("Hello!")return"Done"result=say_hello()# This returns a coroutine object, it does NOT execute yet
print(result)# <coroutine object say_hello at 0x...>
# To actually run the coroutine and get the result, you need to await it:
output=awaitsay_hello()# Now it runs, prints "Hello!" and returns "Done"
print(output)# "Done"
Why does this matter?
Coroutine objects represent tasks that haven’t run yet.
You must await them inside an async function to actually execute the code and get the result.
If you don’t await and just return the coroutine, it’s like returning a “recipe” instead of the “finished dish.”
In your FastAPI app
Your repository functions are async (return coroutine objects).
If you return the coroutine itself (without await), FastAPI tries to serialize the coroutine object, which causes errors.
You must await those async calls so FastAPI gets the actual data to send in the response.
Summary:
Term
Meaning
coroutine function
A function defined with async def
coroutine object
The result of calling a coroutine function — a "lazy" task not yet run
await
The keyword that runs the coroutine and gets its result
Warp outperforms every other coding agent on the market, and gives you full control over which model you use. Get started now for free, or upgrade and unlock 2.5x AI credits on Warp's paid plans.
MongoDB Atlas is the global, multi-cloud database for modern apps trusted by developers and enterprises to build, scale, and run cutting-edge applications, with automated scaling, built-in security, and 125+ cloud regions.
Delve into this thought-provoking piece, celebrated by the DEV Community. Coders from every walk are invited to share their insights and strengthen our collective intelligence.
A heartfelt “thank you” can transform someone’s day—leave yours in the comments!
On DEV, knowledge sharing paves our journey and forges strong connections. Found this helpful? A simple thanks to the author means so much.
Top comments (0)