Promises in JavaScript
Promises in JavaScript
Hello! In this guide, we’ll explore how Promises work in JavaScript. Promises are used to handle asynchronous operations and are an essential part of modern JavaScript programming. Let's dive in!
Video Explanation

1. What is a Promise?
A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises can be in one of three states:
- Pending: The initial state, neither fulfilled nor rejected.
- Fulfilled: The operation completed successfully.
- Rejected: The operation failed.
2. Creating a Promise
A Promise is created using the new Promise() constructor, which takes a function (known as the executor) that contains two callback functions: resolve and reject.
Example:
let promise = new Promise(function (resolve, reject) {
// some async operation
let success = true;
if (success) {
resolve("Operation successful!");
} else {
reject("Operation failed!");
}
});
In this example, the Promise will call resolve if the operation succeeds and reject if it fails.
3. Consuming a Promise
Once a Promise is created, you can use .then(), .catch(), and .finally() to handle its result.
3.1 .then()
The .then() method is used to handle a fulfilled Promise.
Example:
promise.then(function (result) {
console.log(result); // "Operation successful!"
});
3.2 .catch()
The .catch() method is used to handle a rejected Promise.
Example:
promise.catch(function (error) {
console.log(error); // "Operation failed!"
});
3.3 .finally()
The .finally() method is executed once the Promise is settled (either fulfilled or rejected), regardless of the outcome.
Example:
promise.finally(function () {
console.log("Promise is settled.");
});
4. Chaining Promises
You can chain multiple .then() calls together. Each .then() receives the result of the previous .then().
Example:
let promise = new Promise(function (resolve, reject) {
resolve(10);
});
promise
.then(function (result) {
return result * 2;
})
.then(function (result) {
return result + 5;
})
.then(function (result) {
console.log(result); // 25
});
5. Promise Methods
JavaScript provides several built-in methods to work with multiple Promises.