JavaScript Async/Await: From Callbacks to Promises Explained
What is async/await in JavaScript?
async/await is JavaScript syntax for working with promises so that asynchronous code reads like ordinary step-by-step code. A function marked async always returns a promise. Inside it, await pauses that function until a promise settles, then gives you its value or throws its error, while the rest of the page keeps running.
Why JavaScript needs asynchronous code
JavaScript in the browser runs on a single main thread that also handles rendering and user input. If your code waited synchronously for a network request, the page would freeze. Instead, slow operations such as timers, network requests and file reads are started, and your code is notified later when they finish.
| Term | Meaning |
|---|---|
| Call stack | The functions currently running, one frame on top of another |
| Task queue | Callbacks waiting to run, such as timers and events |
| Microtask queue | Promise reactions, run as soon as the stack is empty and before the next task |
| Event loop | The mechanism that takes the next queued work when the stack is empty |
| Promise | An object representing a value that will be available later, or an error |
Browser APIs such as fetch(), timers and file readers do the slow work outside your JavaScript and report back through the queues above. Your job is to describe what should happen when the result arrives, which is exactly what callbacks, promises and async functions express, each more readably than the last.
How the event loop orders your code
The event loop runs all synchronous code first. When the stack is empty, it runs every waiting microtask, then the browser may render, then the loop takes the next task. That is why a resolved promise callback runs before a setTimeout of zero milliseconds.
console.log('1 start');
setTimeout(() => console.log('4 timeout (task)'), 0);
Promise.resolve().then(() => console.log('3 promise (microtask)'));
console.log('2 end');
// 1 start
// 2 end
// 3 promise (microtask)
// 4 timeout (task)Long-running synchronous code still blocks everything, including clicks and painting. Asynchronous syntax does not make heavy calculations faster; it only lets you wait without blocking.
From callbacks to promises to async/await
Early asynchronous code passed callbacks: functions called when work finished. Nesting several in sequence produced deeply indented code that was hard to read and handle errors in.
// Callbacks: each step nests inside the last
getUser(7, (err, user) => {
if (err) return showError(err);
getOrders(user.id, (err, orders) => {
if (err) return showError(err);
render(orders);
});
});A promise is pending, then either fulfilled with a value or rejected with an error. .then() chains the next step and .catch() handles any error from earlier in the chain.
// Promises: a flat chain with one error handler
getUser(7)
.then(user => getOrders(user.id))
.then(orders => render(orders))
.catch(showError)
.finally(() => spinner.hidden = true);
// Wrapping a callback API in a promise
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));async/await is built on promises and lets you write the same flow top to bottom:
async function showOrders(userId) {
spinner.hidden = false;
try {
const user = await getUser(userId);
const orders = await getOrders(user.id);
render(orders);
} catch (error) {
showError(error);
} finally {
spinner.hidden = true;
}
} Error handling in asynchronous code
A rejected promise that is awaited throws, so try/catch works just as it does for synchronous code. A rejection that nobody handles triggers an unhandledrejection event and a console error, and in Node.js it ends the process by default.
- Put
try/catchwhere you can do something useful, such as showing a message, not around every single line. - Always
awaitorreturna promise you create inside an async function; a forgotten promise escapes yourtry/catch. - Throw
Errorobjects rather than strings so you keep a stack trace. - Use
finallyfor clean-up such as hiding a loading indicator.
// Give any promise a time limit with Promise.race
const timeout = (ms) => new Promise((_, reject) =>
setTimeout(() => reject(new Error(`Timed out after ${ms} ms`)), ms));
try {
const report = await Promise.race([buildReport(), timeout(5000)]);
show(report);
} catch (error) {
showError(error.message);
} Running promises in parallel: Promise.all, allSettled, race and any
Two await lines in a row run one after the other. When the requests do not depend on each other, start them together and wait for all of them.
// Sequential: total time = a + b
const courses = await getJSON('/api/courses');
const cities = await getJSON('/api/cities');
// Parallel: total time is roughly the slower of the two
const [courses2, cities2] = await Promise.all([
getJSON('/api/courses'),
getJSON('/api/cities'),
]);
// Keep every result, even when some fail
const results = await Promise.allSettled([getJSON('/a'), getJSON('/b')]);
for (const r of results) {
if (r.status === 'fulfilled') console.log(r.value);
else console.warn(r.reason);
}| Method | Settles when | Use it for |
|---|---|---|
Promise.all | All fulfil, or the first rejects | Results you need together; one failure fails the lot |
Promise.allSettled | Every promise has settled | Independent tasks where partial success is useful |
Promise.race | The first promise settles | Racing a task against a timeout |
Promise.any | The first fulfils, or all reject | Trying several sources and taking the first success |
Practical exercise: a dashboard that loads in parallel
Create three JSON files, courses.json, batches.json and notices.json, serve them from a local server and load them with the Fetch API.
- Write an async
getJSON(url)helper that throws if the response is not OK. - Load the three files sequentially and log the time taken with
performance.now(). - Rewrite it with
Promise.alland compare the time. - Rename one file so its request fails, then switch to
Promise.allSettledso the other two sections still render. - Show a loading message that is always removed in a
finallyblock.
You are done when the parallel version is noticeably faster on a throttled connection, a missing file shows a friendly message in its section only, and no unhandled rejection appears in the console. These patterns are used heavily in SkillNewton's PHP foundation course when front ends talk to PHP endpoints.
Common mistakes
- Forgetting
await, so a variable holds a pending promise instead of the data. - Using
awaitinsideforEachand expecting the loop to wait. - Awaiting independent requests one by one when
Promise.allcould run them together. - Leaving promise rejections unhandled, which hides failures until something else breaks.
- Assuming async code runs on another thread and putting heavy calculations in it.
Frequently asked questions
Can I use await outside an async function?
Only at the top level of an ES module, a feature called top-level await. In classic scripts and ordinary functions, await must be inside an async function. See the modern JavaScript guide for how modules work.
Is async/await better than .then()?
Both use promises underneath. async/await is usually easier to read for sequences and error handling, while .then() is handy for short one-line transformations. Mixing them is fine.
Does an async function run in the background?
No. It runs synchronously until its first await, then pauses and lets other code run. The waiting is non-blocking, but the JavaScript itself still runs on the main thread.
What happens if one promise in Promise.all rejects?
The combined promise rejects with that error straight away. The other operations keep running, but their results are ignored. Use Promise.allSettled if you need every outcome.