5 min read
•Question 5 of 50mediumWhat are Promises in JavaScript?
Understanding Promises for asynchronous operations.
What You'll Learn
- What Promises are
- Promise states
- How to use Promises
What is a Promise?
A Promise is an object representing the eventual completion or failure of an asynchronous operation.
Promise States
| State | Description |
|---|---|
| Pending | Initial state, not fulfilled or rejected |
| Fulfilled | Operation completed successfully |
| Rejected | Operation failed |
Creating a Promise
code.jsJavaScript
const promise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve('Data fetched!');
} else {
reject('Error occurred');
}
});
promise
.then(data => console.log(data))
.catch(error => console.error(error))
.finally(() => console.log('Done'));Promise Methods
code.jsJavaScript
// Wait for all promises
Promise.all([p1, p2, p3])
.then(results => console.log(results));
// First to settle
Promise.race([p1, p2, p3])
.then(result => console.log(result));
// All settled (success or failure)
Promise.allSettled([p1, p2, p3])
.then(results => console.log(results));