Patterns for Dealing with Asynchronous Code
JavaScript runs your code on a single thread, so any work that takes time, such as a network request, a timer or reading a file in Node, has to report back later instead of blocking everything. Over time the language has gained three main patterns for handling that "later": callbacks, promises and async/await. Knowing all three helps you read older code, work with any library and pick the right tool for new code.
Pattern one: callbacks
A callback is a function you pass to another function so it can be called when the work finishes. Browser APIs such as setTimeout and addEventListener use this style, and older Node APIs follow an "error-first" convention where the first argument is an error or null.
const fs = require('fs');
fs.readFile('notes.txt', 'utf8', (err, text) => {
if (err) {
console.error('Read failed:', err.message);
return;
}
console.log(text.length, 'characters read');
});
Callbacks are simple, but they get awkward when steps depend on each other. Each step nests inside the previous one, and error checks repeat at every level.
Pattern two: promises
A promise is an object that stands for a value that is not ready yet. It starts as pending and later becomes either fulfilled with a value or rejected with a reason. You attach handlers with .then() and .catch(), and because .then() returns a new promise, steps can be chained in a flat line instead of nesting.
Promises also give you helpers for groups of tasks: Promise.all, Promise.allSettled, Promise.race and Promise.any.
Pattern three: async and await
This is syntax built on top of promises. An async function returns a promise, and await pauses that function until a promise settles. The same chain you wrote with .then() can be written as straight-line code with ordinary try...catch.
const fs = require('fs/promises');
async function countWords(path) {
try {
const text = await fs.readFile(path, 'utf8');
return text.split(/\s+/).filter(Boolean).length;
} catch (err) {
console.error('Could not count words:', err.message);
return 0;
}
}
Comparing the three side by side
| Pattern | Good for | Watch out for |
|---|---|---|
| Callbacks | Events that fire many times, simple one-off timers | Deep nesting, forgetting to handle the error argument |
| Promises | Chaining steps, combining several tasks | Forgetting to return inside .then(), missing .catch() |
| Async/await | Readable sequences of dependent steps | Awaiting independent tasks one by one, slowing things down |
A mistake people make when mixing patterns
Trouble often starts when a callback API is used inside promise code without converting it. If you call a callback-style function inside an async function, await has nothing to wait for, and the function returns before the work is done. Convert the API first. In Node you can use util.promisify or the built-in promise versions such as fs/promises. In the browser you can wrap a callback in new Promise((resolve, reject) => ...).
The reverse problem also appears: a promise created inside an event handler with no .catch() produces an "unhandled rejection" warning and the error goes unnoticed. Every promise chain needs an end point that handles failure.
Choosing a pattern
Keep callbacks for events that repeat, like clicks or stream data. Use promise helpers when you need to coordinate several tasks at once. Use async/await for most everyday sequences, because it reads top to bottom and handles errors the same way as synchronous code. Under the hood, async/await and promises are the same mechanism, so you can mix them freely once callback APIs are converted.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.