Waiting for a future – async and await
We discussed how one could wait for data from a future inside a co-routine using await. We saw an example that uses await to yield control to other co-routines. Let's now look at an example that waits for I/O completion on a future, which returns data from the web.
For this example, you need the aiohttp
module which provides an HTTP client and server to work with the asyncio module and supports futures. We also need the async_timeout
module which allows timeouts on asynchronous co-routines. Both these modules can be installed using pip.
Here is the code—this is a co-routine that fetches a URL using a timeout and awaits the future, that is, the result of the operation:
# async_http.py import asyncio import aiohttp import async_timeout @asyncio.coroutine def fetch_page(session, url, timeout=60): """ Asynchronous URL fetcher """ with async_timeout.timeout(timeout): response = session.get(url) return response
The following is the calling code with the event...