Skip to content

Promises vs async/await

  • 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.
  • 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).
  • all = all must win.
  • allSettled = report card of all.
  • any = first winner matters.
  • race = first finisher matters.
  • async/await is 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 async function to use await.
    • If async calls can run in parallel, await might make them slower unless you use Promise.all.
  • ๐Ÿ‘‰ 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);
}
  • 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.

FeaturePromises (.then)Async/Await (await)
ReadabilityHarder with chainingCleaner, looks synchronous
Error Handling.catch()try...catch
Parallel ExecutionEasier with .allUse Promise.all
Use CaseWhen chaining simple opsWhen 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.โ€