Promises vs async/await
๐น 1. Promises
Section titled โ๐น 1. Promisesโ- A Promise represents a value that will be available sometime in the future (either resolved or rejected).
- Eg:
function getData(){ const promise = new Promise((resolve, reject)=>{ setTimeout(()=>{ resolve("โ
Data received") }, 100) }) return promise }
// consuming promise getData().then((data)=> console.log(data)).catch((err)=> console.log(err))- โ
Pros:
- Better than callbacks (avoids callback hell).
- Can chain multiple async operations with
.then()
- โ Cons:
- Readability suffers with multiple
.then()chains(becomes Promise hell). - Error handling needs
.catch()at the end.
- Readability suffers with multiple
Promise combinators
Section titled โPromise combinatorsโPromise.all([p1, p2, ...])โ Runs all in parallel, resolves when all succeed, rejects if any one fails.Promise.allSettled([p1, p2, ...])โ Runs all in parallel, waits for all to finish, returns results (fulfilled or rejected).Promise.any([p1, p2, ...])โ Resolves as soon as any one succeeds, rejects only if all fail.Promise.race([p1, p2, ...])โ Resolves/rejects with the first promise that settles (success or failure).
๐ Think of it like:
Section titled โ๐ Think of it like:โall= all must win.allSettled= report card of all.any= first winner matters.race= first finisher matters.
๐น 2. Async/Await
Section titled โ๐น 2. Async/Awaitโasync/awaitis a syntactic sugar on top of Promises -> makes async code looks like synchronous code.- Eg:
const fetchData = async () => { try{ const data = await getData() // waits until resolved. console.log(data) } catch(err){ console.log(err) } }
fetchData()- โ
Pros:
- Much cleaner & more readable (looks like synchronous code).
- Easier error handling with
try...catch. - Great when you have multiple async calls in sequence.
- โ Cons:
- You must be inside
asyncfunction to useawait. - If async calls can run in parallel,
awaitmight make them slower unless you usePromise.all.
- You must be inside
๐น 3. Parallel vs Sequential
Section titled โ๐น 3. Parallel vs Sequentialโ- ๐ Sequential execution (slower, but sometimes required):
async function sequential() { const a = await getData(); const b = await getData(); console.log(a, b); }- ๐ Parallel execution (faster):
async function parallel() { const [a, b] = await Promise.all([getData(), getData()]); console.log(a, b); }๐น 4. Node.js vs Browser Context
Section titled โ๐น 4. Node.js vs Browser Contextโ-
Node.js: Often used for file system, database queries, API calls. Async/await is widely preferred for readability.
-
Browser: Promises and async/await are both used in fetch calls, event handling, etc.
๐น 5. Summary Table
Section titled โ๐น 5. Summary Tableโ| Feature | Promises (.then) | Async/Await (await) |
|---|---|---|
| Readability | Harder with chaining | Cleaner, looks synchronous |
| Error Handling | .catch() | try...catch |
| Parallel Execution | Easier with .all | Use Promise.all |
| Use Case | When chaining simple ops | When dealing with complex async flow |
- ๐ Think of it like this:
- Promise = โIโll do it, call me back when Iโm done.โ
- Async/Await = โWait here until I finish, then continue.โ