Code-Memo

Asynchronous Programming

async and await Syntax

import asyncio

async def async_task():
    print("Task started")
    await asyncio.sleep(1)
    print("Task completed")

# Running an asynchronous coroutine
asyncio.run(async_task())

Asynchronous I/O Operations

Asynchronous I/O operations involve tasks that wait for external resources. Asyncio provides mechanisms to handle these operations efficiently without blocking the event loop.

Asynchronous HTTP Request with aiohttp
import aiohttp
import asyncio

async def fetch_data(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

async def main():
    url = 'https://jsonplaceholder.typicode.com/posts/1'
    response = await fetch_data(url)
    print(response)

asyncio.run(main())

Why do we use Async?