Promises and async/await
Some work takes time: loading data from an API, reading a file, waiting for a timer. JavaScript doesn't stop and wait. It starts the task, keeps running other code, and handles the result later. This is asynchronous programming.
Callbacks and timers
Notice the order: 3 prints last, even though it appears in the middle of the code.
Promises
A Promise is an object representing a value that will arrive later. It is in one of three states: pending, fulfilled (success) or rejected (error).
async / await
async/await lets you write asynchronous code that reads top-to-bottom like normal code. await pauses only this function until the promise settles.
Use try/catch around await to handle errors. It replaces .catch().
Running tasks in parallel
Awaiting one by one is slow when tasks don't depend on each other. Promise.all runs them together.
| Helper | Resolves when… |
|---|---|
Promise.all |
All succeed (rejects on the first failure) |
Promise.allSettled |
All finish, success or failure |
Promise.race |
The first one settles |
Promise.any |
The first one succeeds |
Real world: fetch
In a browser or Node.js, fetch loads data from an API and returns a promise:
async function loadPosts() {
const res = await fetch('https://api.example.com/posts');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const posts = await res.json();
return posts;
}Always check res.ok. fetch only rejects on network failure, not on 404 or 500 responses.
Practice
Write an async function retry(fn, times) that calls fn() and, if it throws, tries again up to times attempts before giving up. Test it with the flaky function below.
1.What does an async function always return?
2.You need three independent API calls. What's fastest?