Asynchronous JS
Promises & async/await
Modern ways to work with asynchronous results.
A Promise represents a value that may not be ready yet. It is in one of three states: pending, fulfilled, or rejected, and settles exactly once.
A promise is a restaurant buzzer — you get it immediately, and it goes off (resolves) when your food is ready, so you are not stuck standing at the counter.
Key concepts
1
.then / .catch chain steps together and flatten nested async work, replacing "callback hell". Promise.all runs work in parallel and fails fast; Promise.allSettled waits for every result regardless of failures.
.then.catchPromise.allPromise.allSettled
2
async/await is syntactic sugar over promises: an async function returns a promise, and await pauses inside it until the awaited promise settles — letting you write async code that reads top-to-bottom. Wrap awaits in try/catch to handle rejection.
async/awaitasyncawaittry/catch
javascript
async function loadUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error('Not found');
return await res.json();
} catch (err) {
console.error(err);
return null;
}
}
// Run in parallel
const [a, b] = await Promise.all([loadUser(1), loadUser(2)]);