JavaScript Promises
A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation. It helps handle asynchronous code without callback hell.
🔹 Why Use Promises?
✅ Avoids Callback Hell (nested callbacks)
✅ Better error handling with .catch()
✅ Can chain multiple async operations
🔹 Creating a Basic Promise
A Promise has three states:
- Pending – Initial state
- Fulfilled – When resolved successfully (
resolve()
) - Rejected – When an error occurs (
reject()
)
✅ Output (after 2 seconds):
✔ If success
is false
, it will go to .catch()
instead.
🔹 Chaining Promises
Promises can be chained to handle multiple asynchronous steps in order.
✅ Output (with delays):
✔ Each step executes after the previous one completes.
🔹 Handling Errors with .catch()
If an error occurs in any .then()
, .catch()
will handle it.
✅ Output:
✔ .catch()
prevents the app from crashing.
🔹 Using Promise.all()
Promise.all()
runs multiple promises in parallel and waits for all to resolve.
✅ Output (after 2 seconds):
✔ If any promise fails, Promise.all()
will reject.
🔹 Using Promise.race()
Promise.race()
returns the result of the first resolved promise.
✅ Output (after 1 second):
✔ The fastest promise wins.
🔹 Using async/await
with Promises
Instead of .then()
, use async/await
for cleaner code.
✅ Output:
✔ Makes async code look synchronous!
🔹 Summary
✔ A Promise handles asynchronous operations
✔ .then()
for success, .catch()
for errors
✔ Chaining helps avoid callback hell
✔ Promise.all()
waits for all, Promise.race()
returns first
✔ Use async/await
for cleaner code
🚀 Need more details? Let me know! 😊