JavaScript started in the 1990s as a way to add a little life to static web pages. Today it runs interactive sites, single-page apps, mobile apps through frameworks like React, and servers through Node.js.
One feature makes all of that possible: asynchronous programming. This guide explains what it is, the three main ways to write it, and how they relate, with a small example you can run.
What is asynchronous programming?
Traditional code runs step by step: start a task, wait for it to finish, then move on. Asynchronous code starts a task and keeps going while it runs in the background. When the result arrives, the program picks it up.
That brings three benefits:
- A better user experience. The page stays responsive while work happens in the background.
- Better performance. Waiting time (for a network call, a file, a timer) is used for other work.
- Scalability. Servers and real-time apps can handle many users at once.
A practical example
Picture a weather app. The old way: fetch the data, wait, then update the screen, with a frozen page in between. The asynchronous way: request the data, keep showing what you already have, and update the screen the moment fresh data arrives.
Four approaches in JavaScript
| Approach | What it is | Restaurant analogy |
|---|---|---|
| Callbacks | A function passed to another function, run when a task finishes | The waiter brings your food when it's ready |
| Promises | An object that stands for a future result (or failure) | A receipt that guarantees your meal, even if it takes a while |
| async/await | Syntax on top of promises that reads like normal code | You read a magazine and pick up where you were when the food arrives |
| Web Workers | Separate threads for heavy work | Assistant chefs in a second kitchen |
Which one to use depends on how complex the work is, how readable the code must be, and whether the job is CPU-heavy (Web Workers) or mostly waiting (the other three). Every modern browser supports async/await, so it's the usual choice today.
The rest of this guide covers callbacks, promises and async/await.
Callbacks
A callback is a function you pass to another function so it can be run later.
- A function that does something asynchronous accepts a callback as an argument.
- It starts the operation (fetching data, waiting for a click).
- When the operation finishes, it calls your callback with the result.
Callbacks are simple, but they nest badly. Three or four dependent steps quickly turn into the "pyramid" known as callback hell. Promises were introduced to fix that.
Promises
A promise is an object representing the eventual result of an asynchronous operation. It's always in one of three states:
- Pending : the operation is still running.
- Fulfilled : it succeeded, and the promise holds the result.
- Rejected : it failed, and the promise holds the error.
You react to the outcome with .then() for success and .catch() for errors. Compared with callbacks, promises give you:
- Readability: flat chains instead of nested pyramids.
-
Easier error handling: one
.catch()can handle errors from the whole chain. - Sequencing: chained steps run in a clear order.
Promises have drawbacks too. Long chains can still be hard to follow ("promise hell"), and the extra layer takes some getting used to. That led to async/await.
async/await
Introduced in ECMAScript 2017, async and await are a cleaner way to write promise-based code:
-
asyncmarks a function as asynchronous. It always returns a promise. -
awaitpauses that function until a promise settles, then gives you its value. The rest of the program keeps running.
The result is code that reads top to bottom, like the steps you would describe out loud, with ordinary try/catch for errors.
How async/await relates to promises
async/await doesn't replace promises; it's built on them.
-
The request: an
asyncfunction starts an operation that returns a promise. -
The wait:
awaitpauses the function, not the whole program. - The resolution: the promise fulfils or rejects.
-
The continuation: the function resumes with the value, or jumps to
catchwith the error.
A worked example: square roots
1. A promise-based function (with a one-second delay to simulate slow work):
function calculateSquareRoot(number) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (number >= 0) {
resolve(Math.sqrt(number));
} else {
reject(new Error("Cannot calculate the square root of a negative number"));
}
}, 1000);
});
}
2. Using it with async/await:
async function calculateSquareRootAsync(number) {
try {
const result = await calculateSquareRoot(number);
console.log("Square root:", result);
} catch (error) {
console.error("Error:", error.message);
}
}
calculateSquareRootAsync(9); // Square root: 3
calculateSquareRootAsync(-4); // Error: Cannot calculate the square root of a negative number
What's happening:
-
calculateSquareRootcreates a promise. Its executor resolves with the square root, or rejects for negative numbers. -
calculateSquareRootAsyncis markedasync, so it can useawait. -
awaitpauses the function until the promise settles. On success the value is logged; on failure,catchhandles the error.
Key takeaways
- Promises are the foundation; async/await is friendlier syntax on top.
-
asyncfunctions always return promises. -
awaitpauses only the current function until the promise settles. - Understanding promises makes async/await much easier to use well.
Further reading: Asynchronous JavaScript on MDN, Promise reference and async function reference.
Building an API next? Read REST APIs explained with simple examples.
Originally published at abhisek-goswami.com.
Top comments (0)