Async/Await in
JavaScript
Master the modern syntax for asynchronous programming: write non-blocking code that reads like synchronous, step-by-step logic.
What Is Asynchronous Code?
JavaScript runs on a single thread: it can only do one thing at a time. When your program needs to fetch data from a server, read a file, or wait for a timer, it cannot freeze the entire page while waiting. Asynchronous code lets JavaScript start a task, move on to other work, and come back when the result is ready.
The Evolution of Async Patterns
JavaScript async patterns evolved from tangled callbacks to chainable Promises, and finally to async/await: syntactic sugar over Promises that makes asynchronous code look and behave like synchronous code.
Quick Recap: Promises
A Promise is an object that represents a value that may not exist yet. It has three states:
The async Keyword
Placing async before a function declaration does two things:
42, callers receive Promise.resolve(42).async, using await is a syntax error.The await Keyword
await pauses execution of the async function until the Promise it is waiting on settles. The resolved value is returned directly, so you can assign it to a variable just like synchronous code.
Under the Hood: Execution Flow
.then() vs async/await
Error Handling: try/catch
When a Promise rejects inside an async function, it throws just like a regular error. Wrap your await calls in try/catch to handle failures gracefully.
How to Apply Async/Await
async keyword before your function declaration or expression.Example 1: Basic Fetch
Goal: fetch a user object from an API and display the name.
Example 2: Sequential vs Parallel
Example 3: Arrow Functions & Loops
Common Mistakes
await in a regular function causes a SyntaxError. Always mark the function as async.await gives you a Promise object instead of the resolved value. Your variable holds [object Promise]..catch() to the returned Promise.Comparison Summary
| Callbacks | .then() Chains | Async/Await | |
|---|---|---|---|
| Readability | Poor (nesting) | Moderate | Excellent |
| Error Handling | Manual checks | .catch() | try/catch |
| Debugging | Hard | Medium | Easy |
| Sequential Flow | Pyramid of doom | Flat chains | Line by line |
| Parallel | Manual | Promise.all() | Promise.all() |
| Return Value | None (callback) | Promise | Promise |
Question 1 of 5
What does an async function always return?
return 42, the caller receives Promise.resolve(42).Question 2 of 5
What happens if you use await inside a function that is not marked as async?
Question 3 of 5
Which approach runs two independent async operations in parallel?
Question 4 of 5
How should you handle a rejected Promise inside an async function?
Question 5 of 5
What value does the variable result hold after this code runs?
result is Promise {<fulfilled>: 10}. You would need await demo() to get 10.