JavaScript Async/Await
Asynchronous JavaScript — promises, async/await, and error handling
What you'll learn
Understand synchronous vs asynchronous execution in JavaScript
Use callbacks and recognize callback hell patterns
Master Promises with .then() and .catch() chains
Write async/await syntax for cleaner asynchronous code
Handle errors in async operations with try/catch
Run multiple async operations in parallel with Promise.all
JavaScript is single-threaded. Async/await handles asynchronous operations without blocking.
Callbacks → Promises → Async/Await
// Callback (old)
fs.readFile("data.json", (err, data) => {
if (err) console.error(err)
else process(data)
})
// Promise
fetch("/api/data")
.then((res) => res.json())
.then((data) => console.log(data))
.catch((err) => console.error(err))
// Async/Await (modern)
async function loadData() {
try {
const res = await fetch("/api/data")
const data = await res.json()
console.log(data)
} catch (err) {
console.error(err)
}
}
Parallel Execution
// Sequential (slower)
const a = await fetchA()
const b = await fetchB()
// Parallel (faster)
const [a, b] = await Promise.all([fetchA(), fetchB()])
// Race — first to resolve wins
const result = await Promise.race([fetchA(), fetchB()])
Error Handling
async function safeFetch(url: string) {
try {
const res = await fetch(url)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return await res.json()
} catch (err) {
console.error(`Fetch failed: ${url}`, err)
return null
}
}
Next Steps
Key Takeaways
JavaScript is single-threaded and uses an event loop to handle asynchronous operations
Promises represent values that may not be available yet and can be chained with .then()
async/await provides synchronous-looking syntax for Promise-based code
Error handling in async code requires try/catch blocks or .catch() on promises
Promise.all runs multiple promises in parallel and fails fast on any rejection