Javascript Promise 🤞

Hello developers,
Today we are going to learn everything about Promises in JAVASCRIPT

A Promise in JavaScript is an object representing the eventual completion or failure of an asynchronous operation. In simpler words, a Promise is a placeholder for the result of an asynchronous operation that can be in one of the following states:

👉Pending: The initial state of a Promise, representing that the asynchronous operation is still in progress.

👉Fulfilled: The state of a Promise representing that the asynchronous operation has completed successfully and the Promise has a value.

👉Rejected: The state of a Promise representing that the asynchronous operation has failed and the Promise has a reason for the failure.

A Promise is created using the Promise constructor, which takes in a callback function as an argument. This callback function, known as the executor function, contains the logic for performing the asynchronous operation and should call either the resolve or reject functions, depending on whether the operation was successful or not.

Here's a simple example to illustrate the use of Promises in JavaScript:
// Example of a Promise that resolves after a set timeout
const wait = time => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('The wait is over');
}, time);
});
};

// Using the Promise
wait(3000).then(result => {
console.log(result);
});
In this example, the wait function returns a Promise that will resolve with the message "The wait is over" after 3000 milliseconds. The then method is used to access the value of the resolved Promise, which is logged to the console.
Note that Promises are asynchronous in nature, so the code following a Promise will continue to execute even if the Promise has not yet resolved or rejected. To perform operations based on the value of a resolved Promise, you can use the then method, which takes in two callback functions as arguments. The first callback function will be called with the resolved value if the Promise is fulfilled, while the second callback function will be called with the rejected reason if the Promise is rejected.
Example 2:
wait(3000)
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error);
});
In this example, the catch method is used to handle any error that might occur in the asynchronous operation. The catch method takes in a single callback function that will be called with the rejected reason if the Promise is rejected.
Promises are a powerful tool for managing asynchronous operations in JavaScript and provide a clean and concise way of handling errors and values returned from asynchronous.