Member-only story

The Magic of Asynchronous JavaScript

Under the Hood of Callbacks, Promises and Async/Await

Max N
3 min readMar 1, 2024
Photo by pine watt on Unsplash

JavaScript started off as a simple scripting language, running code line-by-line in a single thread. But as websites and web apps grew more complex, there needed to be a way to handle expensive operations like network requests without blocking the main thread and freezing the UI.

Enter asynchronous JavaScript.

In this article, we’ll take a magic carpet ride under the hood to understand the core concepts behind asynchronous JavaScript: callbacks, promises and the async/await syntax. Knowing how these work sets you up to write optimized code that keeps your users happy.

Callbacks — A Simple Beginning

The most basic way to introduce asynchronicity in JS is with callback functions. These are functions you pass to another function to be executed later.

function doStuff(callback) {
// do stuff
callback(); // callback is executed async after function completes
}

doStuff(() => {
// this callback function runs after doStuff finishes
});

The key benefit is that doStuff() can complete all its work without blocking execution of the remaining code. The callback gets put in a queue and is invoked asynchronously once doStuff()…

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet