JavaScript
Async JavaScript
JavaScript is single-threaded but handles async operations (network requests, timers) without blocking the UI using the event loop. The modern way to write async code is with async/await built on Promises.
// ── async/await with fetch() ────────────────────────────────────────
async function getUser(userId) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const user = await response.json(); // parse JSON body
console.log(user.name, user.email);
return user;
} catch (error) {
console.error("Failed:", error.message);
return null;
}
}
getUser(1); // call the async function (returns a Promise)
// ── Promise methods ─────────────────────────────────────────────────
// Promise.all — run in PARALLEL, wait for ALL to finish
const [posts, users] = await Promise.all([
fetch("/api/posts").then(r => r.json()),
fetch("/api/users").then(r => r.json()),
]);
// Promise.race — resolve/reject with FIRST settled
// Promise.allSettled — wait for ALL regardless of outcome
// Promise.any — resolve with FIRST fulfilled
// ── Timers ──────────────────────────────────────────────────────────
// Run once after a delay
const timerId = setTimeout(() => {
console.log("Runs after 2 seconds");
}, 2000);
clearTimeout(timerId); // cancel before it fires
// Run repeatedly
const intervalId = setInterval(() => {
console.log("Runs every 1 second");
}, 1000);
clearInterval(intervalId); // stop it
// ── Promise chaining (older style, still valid) ─────────────────────
fetch("https://api.github.com/users/torvalds")
.then(response => response.json())
.then(user => console.log(user.name))
.catch(error => console.error(error));
💡
Always use try/catch with async/await. Without it, unhandled promise rejections can fail silently or crash your app. In Promise.all(), if one promise rejects, the entire call rejects — use Promise.allSettled() if you need results from all requests regardless of individual failures.
Watch & Learn
A recommended video to watch alongside this chapter.
More “Async JavaScript” videos on YouTube