JavaScript promises might sound a bit complicated at first, but once you get a clear understanding of them, they make working with code that takes time to complete, like fetching data from a website or waiting for a timer, much easier to manage. Let’s break down what promises are and how you can use them.
What is a Promise?
A promise in JavaScript is like a container for a future value. It is a way of saying, “I don’t have this value right now, but I will have it later.” Imagine you order a book online. You don’t get the book right away, but the store promises to send it to you. While you wait, you can do other things, and when the book arrives, you can read it.
In the same way, a promise lets you keep working with your code while waiting for something else to finish, like loading data from a server. When the data is ready, the promise will deliver it.
How Does a Promise Work?
A promise can be in one of three states:
- Pending: The promise is waiting for something to finish. For example, waiting for data to load from a website.
- Fulfilled: The promise has been completed successfully. The data you were waiting for is now available.
- Rejected: The promise has failed. Maybe there was a problem, like the server not responding.
When you create a promise, you write some code that will eventually tell the promise whether it was successful (fulfilled) or not (rejected).
Syntax
let promise = new Promise(function(resolve, reject){
//do something
});Parameters
- The promise constructor takes only one argument which is a callback function
- The callback function takes two arguments, resolve and reject
- Perform operations inside the callback function and if everything went well then call resolve.
- If desired operations do not go well then call reject.
Creating a Promise
Let’s see how to create the promise in JavaScript:
Here we have created a new promise using the Promise constructor. Inside the promise, there are two functions: resolve and reject. If everything goes well, we call resolve and pass the result. If something goes wrong, we call reject and pass an error message.
JavaScript
let myPromise = new Promise(function(resolve, reject) {
// some code that takes time, like loading data
let success = true; // change this to false to check error
if (success) {
resolve("The data has loaded successfully!");
} else {
reject("There was an error loading the data.");
}
});
Using a Promise
Once you have a promise, you can use it to do something when it’s fulfilled or rejected. You can do this using two methods: then and catch.
JavaScript
myPromise.then(function(message) {
// This runs if the promise is fulfilled
console.log(message);
}).catch(function(error) {
// This runs if the promise is rejected
console.log(error);
});
Here’s what’s happening:
- The then method is called when the promise is fulfilled. It takes a function as an argument, which will run when the promise is successful.
- The catch method is called when the promise is rejected. It also takes a function, which will run if there’s an error.
So, if the promise is successful, you will see “The data has loaded successfully!” in the console. If there’s an error, you will see “There was an error loading the data.”
Example of Using Promise
We will create a promise comparing two strings. If they match, resolve; otherwise, reject. Then, log success or error accordingly. Simplifies asynchronous handling in JavaScript.
JavaScript
let promise = new Promise(function (resolve, reject) {
const x = "geeksforgeeks";
const y = "geeksforgeeks"
if (x === y) {
resolve();
} else {
reject();
}
});
promise.
then(function () {
console.log('Success, You are a GEEK');
}).
catch(function () {
console.log('Some error has occurred');
});
OutputSuccess, You are a GEEK
Now, that we have learned about how we can create promise let’s see promise consumers that how we can consume them.
Promise Consumers
Promises can be consumed by registering functions using .then and .catch methods.
1. Promise then() Method
Promise method is invoked when a promise is either resolved or rejected. It may also be defined as a carrier that takes data from promise and further executes it successfully.
Parameters: It takes two functions as parameters.
- The first function is executed if the promise is resolved and a result is received.
- The second function is executed if the promise is rejected and an error is received. (It is optional and there is a better way to handle error using .catch() method
Syntax:
.then(function(result){
//handle success
}, function(error){
//handle error
})Example 1: This example shows how the then method handles when a promise is resolved
JavaScript
let promise = new Promise(function (resolve, reject) {
resolve('Geeks For Geeks');
})
promise
.then(function (successMessage) {
//success handler function is invoked
console.log(successMessage);
}, function (errorMessage) {
console.log(errorMessage);
});
Example 2: This example shows the condition when a rejected promise is handled by second function of then method
JavaScript
let promise = new Promise(function (resolve, reject) {
reject('Promise Rejected')
})
promise
.then(function (successMessage) {
console.log(successMessage);
}, function (errorMessage) {
//error handler function is invoked
console.log(errorMessage);
});
2. Promise catch() Method
Promise catch() Method is invoked when a promise is either rejected or some error has occurred in execution. It is used as an Error Handler whenever at any step there is a chance of getting an error.
Parameters: It takes one function as a parameter.
- Function to handle errors or promise rejections.(.catch() method internally calls .then(null, errorHandler), i.e. .catch() is just a shorthand for .then(null, errorHandler) )
Syntax:
.catch(function(error){
//handle error
})Examples 1: This example shows the catch method handling the reject function of promise.
JavaScript
let promise = new Promise(function (resolve, reject) {
reject('Promise Rejected')
})
promise
.then(function (successMessage) {
console.log(successMessage);
})
.catch(function (errorMessage) {
//error handler function is invoked
console.log(errorMessage);
});
Why Use Promises?
Before promises, handling code that took time to complete, like loading data, was more difficult. You had to use something called callbacks, which could get messy and hard to follow, especially when you had to do several things in a row. Promises make this easier by providing a clear way to work with asynchronous code (code that doesn’t run right away). They help you write code that is easier to read and maintain.
Chaining Promises
Sometimes, you need to do several things one after another, like load some data, process it, and then display it. With promises, you can do this by chaining then methods:
JavaScript
fetchData().then(function(data) {
console.log("Data received:", data);
// Suppose this is another function that returns a promise
return processData(data);
}).then(function(processedData) {
console.log("Processed data:", processedData);
}).catch(function(error) {
console.log("Error:", error);
});
In this example:
- The first then gets the data and passes it to processData.
- processData returns another promise.
- The second then handles the result of processData.
- If anything goes wrong along the way, the catch handles the error.
Supported Browsers:
FAQs – JavaScript Promise
How do Promises work in JavaScript?
Promises use then() and catch() methods to handle asynchronous results, allowing chaining of operations.
What are the states of a Promise?
Promises have three states: pending (initial state), fulfilled (successful completion), and rejected (failure).
How do you create a Promise in JavaScript?
Promises are created using the new Promise() constructor, which takes an executor function with resolve and reject parameters
What is Promise chaining?
Promise chaining is the practice of sequentially executing asynchronous operations using multiple then() calls on a Promise.
Can Promises be canceled in JavaScript?
Promises cannot be canceled natively, but techniques like using an external flag or a custom implementation can simulate cancellation.
We have a complete list of Javascript Promise methods, to check those please go through the Javascript Promise Reference article.
Please Login to comment...