CodexBloom - Programming Q&A Platform

Python 3.11: Why does my async function return None instead of expected value?

๐Ÿ‘€ Views: 2 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-01
python asyncio coroutines Python

I've tried everything I can think of but I'm sure I'm missing something obvious here, but Quick question that's been bugging me - I'm experiencing an scenario with my async function where it seems to return `None` instead of the expected list of results... Hereโ€™s a simplified version of what Iโ€™m trying to achieve: ```python import asyncio async def fetch_data(id): await asyncio.sleep(1) # Simulating I/O operation return f'Data {id}' async def main(): tasks = [fetch_data(i) for i in range(5)] results = await asyncio.gather(*tasks) return results output = main() print(output) # Should print a list of fetched data ``` I expected `output` to be a list like `['Data 0', 'Data 1', 'Data 2', 'Data 3', 'Data 4']`, but instead, I get `None`. I tried modifying the function calls and added print statements to debug, but I still need to figure out why the results aren't returned as expected. When I run the code, I also noticed this warning: ``` RuntimeWarning: coroutine 'main' was never awaited ``` Iโ€™m using Python 3.11, and I've ensured that Iโ€™m using the `asyncio` library correctly. Iโ€™ve researched this scenario and found out that I need to await the `main()` function, but Iโ€™m not sure how to do that properly outside of another async context. Should I be using `asyncio.run(main())` instead? How do I implement that without altering the structure of my code too much? Any advice would be greatly appreciated! I'm working on a API that needs to handle this. What's the best practice here? This is part of a larger service I'm building. Any ideas what could be causing this? Any help would be greatly appreciated!