A Promise
is an object that represents the eventual completion or failure of an asynchronous operation. It’s initially in a pending state. It can then transition to either a fulfilled state when the operation is successful, or a rejected state when the operation fails. Here’s an example of creating a Promise
:
const aPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Operation successful!");
}, 1000);
});
In this example, we create a promise that simulates an asynchronous operation using setTimeout
. After one second, the promise is resolved with the message Operation successful!
.
Another way to work with promises is to use the .then
and .catch
methods.
The .then()
method is used in a promise to specify what should happen when the promise is fulfilled, while .catch()
is used to handle any errors that occur. Let’s see how we can use .then
and .catch
with our promise:
aPromise.then((result) => {
console.log(result); // Outputs: "Operation successful!"
}).catch((error) => {
console.error(error);
});
In this code, or instructions of what to do when the promise is fulfilled, the function passed to .then()
will be called with the resolved value of the promise. If an error occurs, the function passed to .catch()
will be called instead.
Now, let’s talk about promise chaining. One of the powerful features of promises is that we can chain multiple asynchronous operations together. Each .then()
can return a new promise, allowing you to perform a sequence of asynchronous operations one after the other. Here’s an example:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data);
return fetch('https://api.example.com/data2');
})
.then(response => response.json())
.then(data2 => console.log(data2))
.catch(error => console.error('Error:', error));
In this example, we’re making two API calls in sequence. The first .then()
parses the response as JSON. The second .then()
logs the data and makes another API call. The third .then()
parses the response of the second API call, and the fourth .then()
logs that data. If an error occurs at any point in this chain, it will be caught by the .catch()
at the end.
It’s important to note that .catch()
will catch errors from any of the previous steps in the chain. This means you don’t need to add error handling to each individual step, which can greatly simplify your code.