JavaScript Promise
JS
What is a Promise?
A Promise is an object in JavaScript that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
It acts like a placeholder for a future value, allowing you to write asynchronous code in a cleaner way than using nested callbacks.
Promise States
A Promise has 3 states:
-
Pending
– initial state, neither fulfilled nor rejected.
-
Fulfilled
– the operation completed successfully, with a result value.
-
Rejected
– the operation failed, with an error reason.
Creating a Promise
resolve(value)
→ moves promise to fulfilled state.reject(error)
→ moves promise to rejected state.
Handling Promises with .then()
and .catch()
.then()
runs when the promise is fulfilled..catch()
runs when the promise is rejected.
Simulating asynchronous operation with setTimeout
javascript CopyEdit
Concept | Meaning |
---|---|
Promise | Represents a future value (or error) |
resolve | Completes successfully (fulfilled) |
reject | Completes with failure (rejected) |
.then() | Handles success |
.catch() | Handles error |
async /await | Cleaner way to write promise-based code |