A
AiTechWorlds
AiTechWorlds
Promises, async/await, Promise.all/allSettled/race/any, error handling, and async iteration β the complete guide.
// Nested callbacks β hard to read and maintain
getUserById(id, function(user) {
getOrdersByUser(user.id, function(orders) {
getProductsForOrder(orders[0].id, function(products) {
console.log(products); // deeply nested
}, handleError);
}, handleError);
}, handleError);Promises and async/await solve this with flat, readable code.
const fetchData = (url) => new Promise((resolve, reject) => {
setTimeout(() => {
if (url.startsWith('https')) {
resolve({ data: 'success', url }); // fulfilled
} else {
reject(new Error('HTTPS required')); // rejected
}
}, 1000);
});| State | Description | Can Transition To |
|---|---|---|
| Pending | Initial state, operation ongoing | Fulfilled or Rejected |
| Fulfilled | Operation completed successfully | (terminal) |
| Rejected | Operation failed | (terminal) |
fetchData('https://api.example.com/users')
.then(response => response.data) // transform
.then(data => JSON.parse(data)) // chain
.then(users => console.log(users))
.catch(error => console.error(error)) // catch any error in chain
.finally(() => console.log('Done')); // always runs// async function always returns a Promise
async function loadUser(userId) {
try {
const response = await fetch(`/api/users/${userId}`); // pauses here
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const user = await response.json(); // pauses here
return user;
} catch (error) {
console.error('Failed to load user:', error);
throw error; // re-throw to caller
}
}
// Arrow function syntax
const getPost = async (id) => {
const res = await fetch(`/api/posts/${id}`);
return res.json();
};// All must succeed β rejects if ANY reject
const [users, posts, comments] = await Promise.all([
fetch('/api/users').then(r => r.json()),
fetch('/api/posts').then(r => r.json()),
fetch('/api/comments').then(r => r.json()),
]);
// All three fetches run simultaneously β much faster than sequential await// Waits for ALL, regardless of success/failure
const results = await Promise.allSettled([
fetch('/api/primary'),
fetch('/api/backup'),
]);
results.forEach(result => {
if (result.status === 'fulfilled') {
console.log('Success:', result.value);
} else {
console.error('Failed:', result.reason);
}
});// Timeout pattern
const timeout = (ms) => new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout')), ms)
);
const result = await Promise.race([
fetch('/api/slow-endpoint'),
timeout(5000) // reject after 5s
]);// Try multiple sources, use whichever succeeds first
const data = await Promise.any([
fetch('/api/primary').then(r => r.json()),
fetch('/api/replica-1').then(r => r.json()),
fetch('/api/replica-2').then(r => r.json()),
]);
// Throws AggregateError only if ALL reject| Method | Resolves When | Rejects When | Returns |
|---|---|---|---|
Promise.all | All fulfilled | Any rejects | Array of results |
Promise.allSettled | All settled (any status) | Never | Array of {status, value/reason} |
Promise.race | First settles | First rejects | Single result |
Promise.any | First fulfills | All reject | Single result |
// SEQUENTIAL β total time = sum of all delays
async function sequential() {
const a = await fetchA(); // wait for A
const b = await fetchB(); // then wait for B
return [a, b];
}
// PARALLEL β total time = max of all delays
async function parallel() {
const [a, b] = await Promise.all([fetchA(), fetchB()]);
return [a, b];
}// Pattern 1: try/catch
async function withTryCatch() {
try {
const data = await riskyOperation();
return data;
} catch (error) {
if (error instanceof NetworkError) handleNetwork(error);
else throw error;
}
}
// Pattern 2: Result tuple (Go-style)
async function safeRun(promise) {
try {
return [null, await promise];
} catch (error) {
return [error, null];
}
}
const [error, data] = await safeRun(fetch('/api/data'));
if (error) return handleError(error);// for await...of β iterate over async iterables
async function processStream(stream) {
for await (const chunk of stream) {
process(chunk);
}
}
// Async generator
async function* paginate(url) {
let page = 1;
while (true) {
const data = await fetch(`${url}?page=${page}`).then(r => r.json());
if (!data.items.length) return;
yield data.items;
page++;
}
}
for await (const items of paginate('/api/products')) {
console.log(items);
}await inside forEach β it doesn't pause forEach, use for...of insteadawait a promise β gets a Promise object instead of the resolved valuePromise.all for parallel executionAdvertisement
Get more notes like this daily on Telegram!
Free study notes, cheat sheets & AI tips
Last reviewed on June 13, 2026 by the AiTechWorlds Notes Team. Free cheat sheet β no signup required.
Advertisement
Join AiTechWorlds on Telegram and get daily AI tips, prompt engineering templates, coding resources, and exclusive content β 100% free!
No spam. Leave anytime.