Member-only story
Getting Started With Asynchronous Programming in Python
Take advantage of the async and await features in asyncio
First Look
In many of our applications, we need to deal with synchronous programming only. This means that code will execute linearly on a single thread. The following code shows you a trivial example:
- The
load_data_for_user
function calls theauthenticate_user
andget_posts_remotely
. - These two functions execute sequentially, taking five seconds to complete, matching the time difference shown in the timestamps.
Apparently, the user experience isn’t too great if the user has to wait five seconds before the data can be displayed. That’s where asynchronous programming can be particularly helpful. Take a look at the following updated code:
If it doesn’t make sense to you now, that’s OK because we’re going to learn asynchronous programming in this article. However, one thing to note is that the total execution time for the same functionalities (i.e., different functions, but get the same jobs done) is reduced to three seconds.
Unlike the synchronous code example shown previously, there are overlaps of the authentication and post fetching functions in this asynchronous code example. In simpler terms, asynchronous programming can launch the next tasks without having to wait for previous tasks to return the results. In other words, synchronous code runs the tasks (e.g., functions) sequentially — execution won’t proceed until the current task completes. By contrast, asynchronous programming allows different tasks to run at the same time.