🚀 JavaScript Promises & Async/Await

📚 What are Promises?

A Promise is an object representing the eventual completion or failure of an asynchronous operation.

Promise States:

🟡 Pending

Initial state, neither fulfilled nor rejected

🟢 Fulfilled

Operation completed successfully

🔴 Rejected

Operation failed

Basic Promise Syntax: new Promise((resolve, reject) => { /* async operation */ })
// Creating a Promise const myPromise = new Promise((resolve, reject) => { const success = true; setTimeout(() => { if (success) { resolve("Operation successful! 🎉"); } else { reject("Operation failed! ❌"); } }, 2000); }); // Using the Promise myPromise .then(result => { console.log("Success:", result); }) .catch(error => { console.log("Error:", error); }) .finally(() => { console.log("Promise completed!"); });

🔗 Promise Chaining

Promises can be chained to handle sequential asynchronous operations:

// Promise Chaining Example function fetchUserData(userId) { return new Promise((resolve) => { setTimeout(() => { resolve({ id: userId, name: "John Doe" }); }, 1000); }); } function fetchUserPosts(user) { return new Promise((resolve) => { setTimeout(() => { resolve([ { title: "Post 1", content: "Hello World" }, { title: "Post 2", content: "Learning Promises" } ]); }, 1000); }); } // Chaining promises fetchUserData(123) .then(user => { console.log("User:", user); return fetchUserPosts(user); }) .then(posts => { console.log("Posts:", posts); return posts.length; }) .then(postCount => { console.log("Total posts:", postCount); }) .catch(error => { console.log("Error:", error); });

🌟 Async/Await

async/await is syntactic sugar over Promises, making asynchronous code look more like synchronous code.

async function functionName() { const result = await promiseFunction(); }
// Converting Promise chain to async/await async function getUserDataAndPosts(userId) { try { console.log("Fetching user data..."); const user = await fetchUserData(userId); console.log("User:", user); console.log("Fetching user posts..."); const posts = await fetchUserPosts(user); console.log("Posts:", posts); const postCount = posts.length; console.log("Total posts:", postCount); return { user, posts, postCount }; } catch (error) { console.log("Error:", error); throw error; } } // Using async function getUserDataAndPosts(123) .then(result => console.log("Final result:", result)) .catch(error => console.log("Caught error:", error));
Key Points about async/await:
  • async functions always return a Promise
  • await can only be used inside async functions
  • await pauses execution until the Promise resolves
  • Use try/catch blocks for error handling

🔄 Promise Methods

Promise.all()

Waits for all promises to resolve or any to reject:

// Promise.all - Wait for all promises const promise1 = new Promise(resolve => setTimeout(() => resolve("First"), 1000)); const promise2 = new Promise(resolve => setTimeout(() => resolve("Second"), 2000)); const promise3 = new Promise(resolve => setTimeout(() => resolve("Third"), 1500)); Promise.all([promise1, promise2, promise3]) .then(results => { console.log("All resolved:", results); // Output: ["First", "Second", "Third"] }) .catch(error => { console.log("One failed:", error); }); // With async/await async function waitForAll() { try { const results = await Promise.all([promise1, promise2, promise3]); console.log("All results:", results); } catch (error) { console.log("Error:", error); } }

Promise.race()

Returns the first promise that settles (resolves or rejects):

// Promise.race - First to finish wins const fastPromise = new Promise(resolve => setTimeout(() => resolve("Fast!"), 1000)); const slowPromise = new Promise(resolve => setTimeout(() => resolve("Slow..."), 3000)); Promise.race([fastPromise, slowPromise]) .then(result => { console.log("Winner:", result); // Output: "Fast!" });

Promise.allSettled()

Waits for all promises to settle, regardless of outcome:

// Promise.allSettled - Wait for all to complete const successPromise = Promise.resolve("Success"); const failPromise = Promise.reject("Failed"); Promise.allSettled([successPromise, failPromise]) .then(results => { console.log("All settled:", results); // Output: [ // { status: "fulfilled", value: "Success" }, // { status: "rejected", reason: "Failed" } // ] });

🎮 Interactive Demo

Click the buttons below to see Promises and async/await in action:

Click a button above to see the output...

📊 Promises vs Async/Await Comparison

Aspect Promises (.then/.catch) Async/Await
Syntax Functional, chain-based Procedural, looks like sync code
Error Handling .catch() or second .then() parameter try/catch blocks
Readability Can become complex with nested chains More readable, especially for complex logic
Debugging Harder to debug, callback-like Easier debugging, step-by-step
Browser Support Older browser support Modern browsers (ES2017+)

🎯 Best Practices

Promise Best Practices:
  • Always handle errors with .catch() or try/catch
  • Use async/await for cleaner, more readable code
  • Use Promise.all() for parallel execution
  • Don't mix .then() with async/await in the same function
  • Return promises from functions when possible
  • Use Promise.allSettled() when you need all results regardless of failures