Asynchronous Javascript

Arjun Gopikrishnan
Gen-Y
Published in
4 min readApr 27, 2020

Javascript, by its very nature as the language of the web tends to have some features and functions that might take a considerable amount of time to complete, for instance, fetching data from a server, API calls and such.

For this very reason, Javascript supports functions that can execute in the background while another chunk of code is executed, known as asynchronous functions.

Confusing? I’ll break it down with a real-world example. Imagine that you’re at a drive-through fast food place. Suppose your order takes lesser time to be prepared than the car ahead of you, however, due to the nature of how a drive through operates, you won’t receive your meal before the person ahead of you.

Compare it to the experience of dining at a restaurant. Suppose I order a cup of coffee, and you order a glass of water after me, you’ll receive your order first since it’s a simpler request.

That is the power of asynchronous Javascript.

Do note that asynchronous does not mean multi-threaded, Javascript is single-threaded.

CALLBACKS

The original way to write asynchronous Javascript was using callbacks. Simply put, a callback is a function that is to be executed after another function has finished executing.

Higher-order functions in Javascript accept functions as arguments. A function that is passed as an argument is called a callback function.

So what’s the problem with callbacks?

When several callbacks get chained together, things can get really ugly. You’ll end up in a place called callback hell.

unpleasant, isn’t it?

The best way to fix callback hell is to not go there at all. Enter Javascript Promises.

Javascript Promises

A promise is an object that may produce a single value some time in the future, which can be a resolved value or an error.

A promise in javascript is similar to real-world promises, a return value is promised, and it is either kept or broken. Promises have 3 possible states, fulfilled, rejected and pending.

A promise takes two callbacks as arguments, which define it’s behaviour upon fulfilment and rejection respectively.

Promise structure

Promises can be chained using the then keyword. Each then block is executed in succession. This entirely solves the problem of callback hell.

promises can be chained by using the .then keyword

Many libraries like axios, fetch and superagent exist to make promise handling easier.

axios in action

ASYNC AND AWAIT

The async keyword, when used in a function automatically returns a promise when it is called using the await keyword. Returning in an async function is basically resolving a promise, or throwing an error upon rejection.

Async functions are simply syntactical sugar-coating for the traditional promise format.

An async function in action.

The await keyword makes the javascript engine wait for the async function to finish before continuing, It is akin to ‘pausing’ the code until an async function is fully executed.

By wrapping our code in try and catch blocks, error handling is a breeze with async functions. They enhance readability in code and enforce modularity, making them a very desirable option while writing asynchronous Javascript.

So in conclusion, I’ll once again list out the key steps to avoid callback hell.

  1. Keep your code shallow.
  2. Modularize your code.
  3. Use function hoisting and handle each and every error in your callbacks. Using a simple linter helps.
  4. Avoid nesting functions. Create all of them separately and call them in your top-level code.
  5. Integrate promises into your program to avoid writing spaghetti code.

Keep in mind, no need to worry about callback hell if you don’t even go there.

--

--