Promise For The Newby, How Promises Works in Javascript
--
What is a Promise?
A Promise is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value. A Promise is used to handle asynchronous operations and provide a way to avoid callback hell.
A Promise can be in one of three states:
- Pending: The initial state. The promise is neither fulfilled nor rejected.
- Fulfilled: The operation completed successfully, and the promise has a resulting value.
- Rejected: The operation failed, and the promise has a reason for the failure.
Creating a Promise
To create a Promise in JavaScript, you use the Promise constructor. The constructor takes a single argument: a function called the “executor” function. The executor function takes two parameters: “resolve” and “reject”. These are functions that you call to change the Promise’s state.
Here’s an example of creating a Promise that resolves with a value after a delay:
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Hello, world!');
}, 1000);
});
In this example, the Promise will resolve with the string “Hello, world!” after a delay of one second.
Consuming a Promise
Once you have created a Promise, you can consume it by calling the then
method on it. The then
method takes two callback functions as parameters: one to handle the fulfillment of the Promise, and one to handle the rejection of the Promise.
Here’s an example of consuming the Promise we created earlier:
promise.then(
(value) => {
console.log(value); // logs "Hello, world!"
},
(reason) => {
console.error(reason);
}
);
In this example, the first callback function is called when the Promise is fulfilled, and the second callback function is called when the Promise is rejected.
Chaining Promises
You can chain Promises together to perform a sequence of asynchronous operations. When you chain Promises, the output of one Promise becomes the input…