Async await
import asyncio
async def fetch_data():
print("Start fetching data...")
await asyncio.sleep(5) # Simulate a network request
print("Data fetched!")
return {"data": "Sample data"}
async def process_data():
print("Start processing data...")
await asyncio.sleep(6) # Simulate data processing
print("Data processed!")
return {"processed_data": "Processed sample data"}
async def main():
# Run fetch_data and process_data concurrently
fetch_task = asyncio.create_task(fetch_data())
process_task = asyncio.create_task(process_data())
print("Something else can be done here...") #not async call
for i in range(10):
print(i)
await asyncio.sleep(1)
# Wait for both tasks to complete (here where await - is blocked)
data = await fetch_task
processed_data = await process_task
print(f"Fetched data: {data}")
print(f"Processed data: {processed_data}")
# Run the main function
asyncio.run(main())
Something else can be done here...
0
Start fetching data...
Start processing data...
1
2
3
4
Data fetched!
5
Data processed!
6
7
8
9
Fetched data: {'data': 'Sample data'}
Processed data: {'processed_data': 'Processed sample data'}
Process finished with exit code 0