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:
- Pending → initial state
- Fulfilled → operation successful
- Rejected → operation failed
promise
.then(result => console.log(result)) // success
.catch(error => console.log(error)); // failureCallback Hell ProblemBefore Promise:
doSomething(() => {
doSomethingElse(() => {
doAnotherThing(() => {
// messy
});
});
});After Promise: Clean & readabledoSomething()
.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);
}
}ChainingfetchData()
.then(data => process(data))
.then(result => save(result));Error Handlingpromise
.then(data => { throw new Error("fail"); })
.catch(err => console.log(err));Event Loop ContextsetTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("promise"));Static Methods
Promise.all()→ parallel execution (fails fast)Promise.allSettled()→ waits for allPromise.race()→ first result winsPromise.any()→ first successA Promise in JavaScript is an object that represents the eventual completionor failure of an asynchronous operation. It allows handling async resultsusing.then,.catch, or async/await, and internally it uses the microtask queuefor execution.
No comments:
Post a Comment