Saturday, April 25, 2026

Node | Promise

A Promise is an object that represents the eventual result (success or failure) of an asynchronous operation.

Think of it as a placeholder for a value that will be available later.

 Ordering food online:

  • You place an order → Promise created
  • Food arrives → Resolved
  • Order cancelled → Rejected

Promise States

A Promise has 3 states:

  1. Pending → initial state
  2. Fulfilled → operation successful
  3. Rejected → operation failed

promise
.then(result => console.log(result)) // success
.catch(error => console.log(error)); // failure

Callback Hell Problem

Before Promise:

doSomething(() => {
doSomethingElse(() => {
doAnotherThing(() => {
// messy
});
});
});

After Promise: Clean & readable
doSomething()
.then(doSomethingElse)
.then(doAnotherThing)
.catch(console.error);


How Promises Work Internally (Important)

When resolved/rejected:

  • They don’t execute immediately
  • They go to Microtask Queue

Event loop executes them:

  • After process.nextTick
  • Before timers / I/O


Async/Await (Modern Way)

Built on top of Promises

async function run() {
try {
const result = await promise;
console.log(result);
} catch (err) {
console.log(err);
}
}


Chaining

fetchData()
.then(data => process(data))
.then(result => save(result));



Error Handling

promise
.then(data => { throw new Error("fail"); })
.catch(err => console.log(err));


Event Loop Context

setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("promise"));


Static Methods
  • Promise.all() → parallel execution (fails fast)
  • Promise.allSettled() → waits for all
  • Promise.race() → first result wins
  • Promise.any() → first success

A Promise in JavaScript is an object that represents the eventual completion
or failure of an asynchronous operation. It allows handling async results
using .then, .catch, or async/await, and internally it uses the microtask queue
for execution.

No comments:

Post a Comment

Node | Cluster Vs Worker Threads

Cluster: Multiple processes (scale app across CPU cores) Worker Threads: Multiple threads (handle CPU-heavy work inside one process) Cluster...