Promise
A Promise in JavaScript is a powerful mechanism for handling asynchronous operations. It represents a value that may be available now, or in the future, or never. Promises have three states:
1. Pending: The initial state. The operation is not completed yet.
2. Fulfilled: The operation is completed successfully, and the promise has a resulting value.
3. Rejected: The operation failed, and the promise has a reason for the failure.
Promises are commonly used when dealing with asynchronous tasks, such as making API calls or handling data fetching.
Creating a Promise:
To create a promise, you use the `Promise` constructor, which takes a function as an argument. This function, in turn, takes two parameters: `resolve` and `reject`. If the asynchronous operation is successful, you call `resolve` with the result. If it fails, you call `reject` with an error.
Example:
Using a Promise:
Once you have a promise, you can use the `.then()` method to handle the fulfillment of the promise or the `.catch()` method to handle any rejection.
Example:
countValue.then(
function(value) {
document. write(“Success:”, value);
},
function(error) {
console.error(“Error:”, error);
}
);
In this example, if the promise is fulfilled, the success callback is executed, and if it is rejected, the error callback is executed.
Key Points:
– Promises are excellent for managing asynchronous code and handling success or failure.
– They provide a cleaner alternative to callback functions, making code more readable and maintainable.
– Promises can be chained together for more complex asynchronous workflows.