πŸ’‘ 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()]);

Disclaimer: The information provided on this website is for educational and informational purposes only. Health-related content is not intended to serve as medical advice, diagnosis, or treatment recommendations and should not replace consultation with qualified healthcare professionals. Financial content is for educational purposes only and does not constitute financial advice, investment recommendations, or professional financial planning services. Always consult with licensed healthcare providers for medical concerns and qualified financial advisors for personalized financial guidance.