Introduction to Asynchronous Programming

Secundino Martinez
4 min readMar 1, 2021

What is the concept?

Have you ever woken up late for work or school, forcing you to shower in 4 minutes flat? If you’re like me then the answer is “yes — frequently.” Over time, in an attempt to maximize efficiency, I learned to begin my showers by applying shampoo, then washing my body while the shampoo sits in my hair before finally rinsing it out. This is an excellent example of performing a set of tasks asynchronously. Instead of waiting around and doing nothing while the shampoo was in my hair, I recognized there was a period where my hair didn’t need my attention. I then leveraged that knowledge by performing other tasks in the interim. This is the essence of Asynchronous Programming.

How does this translate to code?

Solutions for the paradigm

The word ‘asynchronous’ means “not existing or happening at the same time.” Many programming languages have either built-in functionality or external libraries to handle this paradigm. For the purpose of this article, I will use JavaScript (ES6) because it has a simple built-in implementation for async. Other popular solutions include the Python asyncio library, the C++ std::async library, and the PHP Async library.

Reasons for the paradigm

Now that you know what the concept is and what different languages offer to implement it, you’re probably wondering what problems it solves. The most ubiquitous applications for asynchronous programming fall under the Web Development umbrella. API calls, Webhooks, Websockets, and communication from the backend to the frontend of web apps all employ asynchronous programming in one way or another. Let’s say you want to make a website that displays the data provided by Genius’ lyrics API to categorize or access song lyrics. To accomplish this, you will have to send the API a request (something to tell it “I want the lyrics for this song”). When you do this, the API will return a response, but it won’t happen instantly. It may take 0.01 seconds, or it may take 1 second. It may even take 1 minute depending on the API. You don’t want your website to completely halt for that entire amount of time whenever you request lyrics, so implementing asynchronous programming allows your code to continue running while it waits!

Example code

Let’s say you want to show your friends fun cat facts using javascript and the cat facts API. You could try to do this synchronously using Node.js like so:

const fetch = require(‘node-fetch’)
const result = fetch(‘https://cat-fact.herokuapp.com/facts/random')
console.log(result)

But if you do this, the result will be Promise { <pending> }, which is not very useful. There are two possible solutions to this, depending on your preference.

Using promises

If we want our result to actually contain the cat fact, we can treat it as a Promise object, and use the .then() function like so:

const fetch = require('node-fetch')
const result = fetch(
'https://cat-fact.herokuapp.com/facts/random'
).then(

(json) => {
return json
}
)

This will log our actual API data rather than that pending promise we were getting earlier. What .then() does is:

  • Take a callback function to perform later
  • wait until the Promise is no longer “pending” but “resolved” and then perform the callback function with that resolved value.

This solves our issue cleanly and is easily extensible, but maybe isn’t the prettiest code. In my opinion, async/await solution is more intuitive and visually appealing.

Async/await

To achieve the same outcome as our solution with promises but using the ES6 async/await functionality, we can use the following:

const fetch = require('node-fetch')
const awaitResponse = async () => {
const response = await fetch(
'https://cat-fact.herokuapp.com/facts/random'
)
const data = await response.json()
console.log(data)
}
awaitResponse()

This operates the same as our promises solution but doesn’t use .then() anymore. What we are doing here is:

  • Define an async function using the async keyword
  • Inside of that function, we await our asynchronous API call, which will literally wait until it resolves before proceeding
  • We use await again to get the JSON data stored in the result of our API call
  • We then log the JSON data to the console

--

--