A Promise of Asynchronous JavaScript

Solving synchronous problems with callbacks, promises, and async/await

Michael Karén
DailyJS

--

Photo by Daniel Dara on Unsplash

In this article, we discover the problems with synchronous JavaScript and how we can solve them with the asynchronous techniques of callbacks, promises, and async/await.

We go through the three ways one by one with examples to discover how JavaScript has evolved in this area in recent years. However, before looking into these techniques, let’s look into the difference between synchronous and asynchronous code.

Synchronous code

JavaScript is a single-threaded programming language, which means only one thing can happen at a time. While a single thread simplifies writing and reasoning about code, this also has some drawbacks.

Imagine we do a long-running task like fetching a resource over the network. Now we block the browser until the resource is downloaded. This can make for a bad user experience and might result in the user leaving our page.

When we execute code synchronously, we wait for it to finish before moving to the next task. Nothing else can happen while each operation is being processed — rendering is paused.

Let’s write some code to clarify:

--

--

Michael Karén
DailyJS

Frontend Architect • JavaScript Enthusiast • Educative.io Author • ngVikings organizer.