Understanding Async/Await in JavaScript Promises

Day 36/50 – JavaScript Interview Question? Question: What is async/await and how does it relate to Promises? Simple Answer: async/await is syntactic sugar over Promises that makes asynchronous code look and behave more like synchronous code. An async function always returns a Promise, and await pauses execution until a Promise resolves, without blocking the event loop. 🧠 Why it matters in real projects: async/await makes complex asynchronous flows much more readable than Promise chains. It's essential for modern API interactions, database queries, and any sequential async operations. Error handling with try/catch is also more intuitive than .catch(). 💡 One common mistake: Forgetting that await only works inside async functions, or not realizing that await pauses the async function but doesn't block the entire program. Also, using await in loops inefficiently instead of Promise.all(). 📌 Bonus: // Promise chain (harder to read) function getUserPosts() { return fetch('/api/user') .then(res => res.json()) .then(user => fetch(`/api/posts/${user.id}`)) .then(res => res.json()) .then(posts => posts) .catch(error => console.error(error)); } // async/await (cleaner) async function getUserPosts() { try { const userRes = await fetch('/api/user'); const user = await userRes.json(); const postsRes = await fetch(`/api/posts/${user.id}`); const posts = await postsRes.json(); return posts; } catch (error) { console.error(error); throw error; } } // Key concepts: // 1. async function always returns a Promise async function test() { return 'hello'; // Automatically wrapped in Promise } test().then(val => console.log(val)); // "hello" // 2. await pauses the async function, not the program async function demo() { console.log('1'); await delay(1000); console.log('3'); } demo(); console.log('2'); // Prints: 1, 2, 3 // Common mistakes: // ✗ Sequential when parallel is possible (slow) const user = await fetchUser(); const posts = await fetchPosts(); // Waits unnecessarily // ✓ Parallel execution (fast) const [user, posts] = await Promise.all([ fetchUser(), fetchPosts() ]); // ✗ Using await in loops (sequential) for (let id of ids) { await fetchData(id); // Slow! } // ✓ Parallel with Promise.all await Promise.all(ids.map(id => fetchData(id))); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #AsyncAwait #Promises #WebDev #InterviewPrep #ES2017

To view or add a comment, sign in

Explore content categories