1. Basic Async/Await Usage
async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();
2. Sequential vs Parallel Async Calls
// Sequential
async function sequential() {
const a = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const b = await fetch('https://jsonplaceholder.typicode.com/todos/2');
return [await a.json(), await b.json()];
}
// Parallel
async function parallel() {
const [a, b] = await Promise.all([
fetch('https://jsonplaceholder.typicode.com/todos/1'),
fetch('https://jsonplaceholder.typicode.com/todos/2')
]);
return [await a.json(), await b.json()];
}
3. Handling Errors in Async/Await
async function safeAsync(fn) {
try {
return [null, await fn()];
} catch (err) {
return [err, null];
}
}
// Usage
// const [err, result] = await safeAsync(() => fetch(...));
4. Retrying Async Operations
async function retryAsync(fn, retries = 3, delay = 500) {
try {
return await fn();
} catch (err) {
if (retries === 0) throw err;
await new Promise(res => setTimeout(res, delay));
return retryAsync(fn, retries - 1, delay);
}
}
// Usage
// await retryAsync(() => fetch(...));
5. Running Async Functions in a Loop (forEach Pitfall)
// DON'T use forEach with async/await
const arr = [1, 2, 3];
arr.forEach(async (num) => {
await someAsyncFunc(num); // This won't wait as expected!
});
// DO use for...of
for (const num of arr) {
await someAsyncFunc(num);
}
6. Timeout for Async/Await
async function withTimeout(promise, ms) {
let timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout')), ms)
);
return Promise.race([promise, timeout]);
}
// Usage
// await withTimeout(fetch(...), 1000);