JavaScript Promises Explained
๐ What is a Promise?
- A Promise is a special JavaScript object that represents the result of an asynchronous operation.
- Itโs like a placeholder for a value that will be available later (success or failure).
Think: โI promise Iโll give you the result later.โ
๐ฆ The 3 States of a Promise
- Pending โ still waiting for the result.
- Fulfilled โ completed successfully, has a value.
- Rejected โ failed, has a reason (usually an error).
Once a promise is fulfilled or rejected, itโs settled and cannot change again.
๐ How to Create a Promise
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Done! โ
");
// or reject("Something went wrong โ");
}, 1000);
});
- The function inside
new Promise
runs immediately. - Call
resolve(value)
to fulfill. - Call
reject(error)
to fail.
โณ Using a Promise
With .then
and .catch
myPromise
.then(result => console.log(result)) // "Done! โ
"
.catch(err => console.error(err));
With async/await
(sugar syntax)
async function run() {
try {
const result = await myPromise;
console.log(result); // "Done! โ
"
} catch (err) {
console.error(err);
}
}
โก Chaining Promises
You can chain .then
calls to transform values step by step:
fetch("/data.json")
.then(res => res.json())
.then(data => data.items)
.then(items => console.log(items))
.catch(err => console.error(err));
Each .then
returns a new Promise, which makes chaining possible.
๐ Common Mistakes
- Forgetting to return:
.then(() => { doSomething(); }) // โ returns undefined .then(() => doSomething()) // โ returns the promise/value
- Mixing callbacks + promises unnecessarily.
- Not handling errors: Always end with
.catch
or usetry/catch
.
๐ Promise Utilities
Promise.all([p1, p2])
โ waits for all to fulfill, fails fast if one rejects.Promise.race([p1, p2])
โ returns the first settled (fulfilled or rejected).Promise.allSettled([p1, p2])
โ waits for all, returns results with status.Promise.any([p1, p2])
โ first fulfilled, ignores rejections until all reject.
๐ How Promises work under the hood
- Resolvers (
resolve/reject
) queue their reactions as microtasks. - This means
.then
/catch
callbacks always run after the current synchronous code, but before macrotasks likesetTimeout
.
console.log("Start");
Promise.resolve().then(() => console.log("Microtask"));
setTimeout(() => console.log("Macrotask"), 0);
console.log("End");
Output:
Start
End
Microtask
Macrotask
โ Summary
- A Promise is an object that represents future values.
- Has 3 states:
pending
,fulfilled
,rejected
. - Use
.then/.catch
orasync/await
to consume. - Promises are scheduled as microtasks in the event loop, making them powerful for async flow control.
โจ Promises are the foundation of async/await and modern JavaScript concurrency.
How did you like this post?
๐0
โค๏ธ0
๐ฅ0
๐ค0
๐ฎ0