What Is Asynchronous Programming in JavaScript?
Learn what asynchronous programming means in JavaScript, why one thread needs it, and how callbacks, promises and async await let work finish later.

A web page that froze for three seconds every time it asked a server for data would be unusable, and JavaScript runs your code on a single thread. Both facts are true at once, and asynchronous programming is how they coexist. You start slow work such as a network request, a file read or a timer, you keep running other code while it happens, and you handle the result when it arrives. This post explains what that means on Node.js 24 and in current browsers: what "asynchronous" actually describes, why a single thread needs it, the three styles of writing it (callbacks, promises and async/await) and the mistakes beginners make in the first week. Every example prints its output, so you can follow the order in which things happen, which is the whole subject.
What the word means
Synchronous code runs one line after another, and each line finishes before the next starts. Asynchronous code starts an operation and moves on without waiting, then runs a function you supplied when the operation is done. The key point is that the waiting is not done by your code. The runtime, the browser or Node.js, does the waiting, and your thread stays free.
console.log("1: start");
setTimeout(() => {
console.log("3: the timer finished");
}, 0);
console.log("2: end of the script");1: start
2: end of the script
3: the timer finishedThe timer was set to zero milliseconds, and it still printed last. setTimeout does not run its function. It hands the function to the runtime and says "call this later". Your script finishes first, and only then does the runtime call the function. That ordering surprises everyone once, and then it becomes the thing you reason with.
Why one thread needs it
JavaScript has one call stack. While a function runs, nothing else in your program runs. If a function spent two seconds waiting for a server, the page could not scroll, click or repaint for two seconds. So the platform splits the work. The slow part, waiting for the network or the disk, happens outside your thread. When it finishes, a task is queued, and your thread picks it up when the stack is empty.
Here is the same problem in its blocking form, a loop that holds the thread, next to a timer that is supposed to fire in 10 ms.
const start = Date.now();
setTimeout(() => {
const waited = Date.now() - start;
console.log(waited >= 100 ? "timer ran late" : "timer ran on time");
}, 10);
while (Date.now() - start < 100) {
// busy loop, holds the thread for 100 ms
}
console.log("loop finished");loop finished
timer ran lateThe timer was ready after 10 ms, but the loop occupied the only thread for 100 ms, so the callback had to wait. Asynchronous code is not parallel code. It is code that avoids holding the thread while waiting. The moment you write a long synchronous loop, you lose the benefit.
Style 1: callbacks
The oldest style passes a function to be called when the work is done. Node.js uses the error-first convention: the first argument is an error or null.
import { readFile } from "node:fs";
readFile("package.json", "utf8", (error, text) => {
if (error) {
console.log("failed:", error.code);
return;
}
console.log("read", text.length > 0 ? "some text" : "nothing");
});
console.log("request sent");request sent
read some text"request sent" prints first, because readFile returns immediately and the callback runs later. This assumes a package.json exists in the working directory. Callbacks work, and they get hard to read when one step depends on the previous one, because each dependent step nests inside the last.
Style 2: promises
A promise is an object that stands for a result that does not exist yet. It is pending, then it either fulfills with a value or rejects with an error. You attach functions with then and catch.
const wait = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
wait(20, "first")
.then((value) => {
console.log("got", value);
return wait(10, "second");
})
.then((value) => console.log("got", value))
.catch((error) => console.log("failed", error.message));
console.log("chain built");chain built
got first
got secondThe chain is flat, so a sequence of dependent steps reads top to bottom. A rejection anywhere skips to the catch. The code after the chain still ran first, which is the same ordering rule as before.
Style 3: async and await
async/await is syntax over promises. An async function returns a promise, and inside it await pauses that function, not the thread, until a promise settles.
const wait = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function main() {
try {
const first = await wait(20, "first");
console.log("got", first);
const second = await wait(10, "second");
console.log("got", second);
} catch (error) {
console.log("failed", error.message);
}
}
main();
console.log("main called");main called
got first
got secondmain() ran until its first await, handed control back, and the line after the call printed. Then the function resumed when the timer fired. It looks like synchronous code and behaves asynchronously, which is both the appeal and the trap. Anything after an await in that function runs later than the code after the call.
Running things together
Awaiting one after another is correct when a step needs the previous result. It wastes time when the steps are independent, because each waits for the last to finish.
const wait = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const start = Date.now();
const results = await Promise.all([
wait(30, "a"),
wait(30, "b"),
wait(30, "c"),
]);
const elapsed = Date.now() - start;
console.log(results);
console.log(elapsed < 80 ? "ran together" : "ran in sequence");[ 'a', 'b', 'c' ]
ran togetherThree 30 ms waits finished in about 30 ms, not 90, because all three timers were running at once. The comparison uses a generous threshold of 80 ms so the output does not depend on small scheduling differences. Promise.all is the tool for independent work, and it is covered in its own post on running promises in parallel.
Mistakes in the first week
Forgetting to await. Calling an async function without await gives you a promise, not the value.
async function getName() {
return "Ada";
}
console.log(getName());
console.log(await getName());Promise { 'Ada' }
AdaExpecting a loop to wait. forEach does not wait for async callbacks. Use for...of with await, or Promise.all with map.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
[1, 2, 3].forEach(async (n) => {
await wait(10);
console.log("inside", n);
});
console.log("after forEach");
await wait(40);after forEach
inside 1
inside 2
inside 3The line after forEach printed before any callback finished, since forEach ignores the promises its callback returns.
Ignoring errors. A rejected promise nobody handles crashes Node.js on current versions with an unhandled rejection error. Always catch, or await inside try.
When to choose which style
Use async/await by default. It reads in the order things happen, try/catch handles errors, and it composes with Promise.all. Use promises directly when you are combining several of them or building a utility. Use callbacks only where an API gives you nothing else, such as event listeners, which fire many times and do not fit a promise that settles once. Most Node.js APIs now have a promise version in node:fs/promises and similar modules.
What this does not cover
Asynchronous code does not make a slow calculation faster. If a function spends a second crunching numbers, it holds the thread whether it is async or not, because async only changes how results are delivered. For that kind of work, move it to a worker thread. Asynchronous programming helps with waiting, not with computing.
Habits that make async code easier to live with
A few habits pay off early. Name the asynchronous functions so a reader can tell, from the name alone, that a promise comes back: loadUser, fetchOrders, saveDraft. Keep one level of asynchrony per function where you can, so a function either starts work and returns a promise or processes a result, and not both in a tangle. And decide where errors are handled. The usual answer is as close to the user-facing boundary as possible: low-level functions let rejections travel up, and one handler near the top turns them into a message, a retry or a log entry.
Most beginners also underestimate how much of the confusion is about order, not syntax. When a result looks wrong, add a log line before and after each asynchronous call and read the order the lines appear in. Nearly every first-week bug is code that assumed a later line ran after the callback, when the runtime ran it first.


