π‘ Key Takeaways
β³ Async Operations: Promises handle asynchronous code like API calls, timers, and file operations.
π― Three States: Promises are pending, fulfilled, or rejected.
βοΈ Chainable: Use .then() to chain operations sequentially.
π‘οΈ Error Handling: Always use .catch() or try/catch to handle errors.
β¨ Modern Syntax: async/await makes promise code look synchronous and cleaner.
π Creating a Promise
- Takes executor function
- Executor gets resolve and reject
- Returns a Promise object
const promise = new Promise((resolve, reject) => {
if (success) resolve(value);
else reject(error);
});
β then()
- Handles fulfilled promises
- Returns a new promise
- Can be chained
promise
.then(result => console.log(result))
.then(() => 'next step');
β catch()
- Handles rejected promises
- Catches errors in chain
- Should always be included
promise
.then(result => result.data)
.catch(error => console.error(error));
π finally()
- Runs after settled (fulfilled or rejected)
- Good for cleanup
- Doesn't receive any value
promise
.then(result => result)
.catch(error => error)
.finally(() => console.log('Done'));
β‘ Promise.resolve()
- Creates an already-fulfilled promise
- Useful for consistent returns
- Wraps value in promise
const resolved = Promise.resolve(42);
resolved.then(val => console.log(val)); // 42
π« Promise.reject()
- Creates an already-rejected promise
- Good for error scenarios
- Returns rejected promise
const rejected = Promise.reject('Error!');
rejected.catch(err => console.log(err)); // 'Error!'
π€ Promise.all()
- Waits for all promises to resolve
- Returns array of results
- Rejects if any promise fails
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
Promise.all([p1, p2]).then(results => console.log(results)); // [1, 2]
π Promise.race()
- Returns first settled promise
- Resolves or rejects with first result
- Other promises still run
const fast = new Promise(resolve => setTimeout(() => resolve('fast'), 100));
const slow = new Promise(resolve => setTimeout(() => resolve('slow'), 500));
Promise.race([fast, slow]).then(result => console.log(result)); // 'fast'
π₯ Promise.any()
- Returns first fulfilled promise
- Ignores rejections
- Rejects if all promises fail
const p1 = Promise.reject('error');
const p2 = Promise.resolve('success');
Promise.any([p1, p2]).then(result => console.log(result)); // 'success'
π― Promise.allSettled()
- Waits for all to settle
- Never rejects
- Returns array of status objects
const p1 = Promise.resolve(1);
const p2 = Promise.reject('error');
Promise.allSettled([p1, p2]).then(results => console.log(results));
// [{status: 'fulfilled', value: 1}, {status: 'rejected', reason: 'error'}]
π async Function
- Always returns a promise
- Can use await inside
- Makes async code look sync
async function getData() {
return 'data';
}
getData().then(result => console.log(result)); // 'data'
βΈοΈ await
- Pauses until promise settles
- Only works inside async functions
- Returns resolved value
async function fetchData() {
const response = await fetch('/api');
const data = await response.json();
return data;
}
π‘οΈ try/catch with async/await
- Handles errors with async/await
- Cleaner than .catch() chains
- Works like synchronous code
async function getData() {
try {
const result = await fetchAPI();
return result;
} catch (error) {
console.error(error);
}
}
βοΈ Chaining Promises
- Each .then() returns new promise
- Pass data through chain
- Return values become next input
fetch('/api')
.then(response => response.json())
.then(data => data.filter(item => item.active))
.then(filtered => console.log(filtered))
.catch(error => console.error(error));
π Promise vs async/await
- Both handle same operations
- async/await is more readable
- Choose based on preference
// Promise syntax
fetchData().then(result => console.log(result));
// async/await syntax
const result = await fetchData();
console.log(result);
β±οΈ Common Pattern: setTimeout
- Wrap setTimeout in promise
- Useful for delays
- Returns promise that resolves later
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
async function example() {
console.log('Start');
await delay(1000);
console.log('After 1 second');
}
π Common Pattern: fetch API
- Built-in promise-based HTTP
- Returns promise with response
- Need to parse response
async function getUser(id) {
const response = await fetch(`/api/users/${id}`);
const user = await response.json();
return user;
}
π Sequential vs Parallel
- Sequential: one after another
- Parallel: all at once
- Choose based on dependencies
// Sequential
const a = await promise1();
const b = await promise2();
// Parallel
const [a, b] = await Promise.all([promise1(), promise2()]);