“promise” in java script
In JavaScript, a Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. A Promise can be in one of three states:
- Pending: The initial state; 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.
Promises are commonly used for handling asynchronous operations like fetching data from a server, reading and writing files, and making API calls. Using Promises, you can handle the result of an asynchronous operation once it’s ready, without blocking the main thread of execution.
Here’s an example of how to create a Promise in JavaScript:
const promise = new Promise((resolve, reject) => {
// asynchronous operation
const result = fetch('https://example.com/api/data');
if (result) {
resolve(result);
} else {
reject('Error: Failed to fetch data');
}
});
promise.then(result => {
console.log(result);
}).catch(error => {
console.error(error);
});
In the example above, a Promise is created using the new Promise()
constructor, which takes a function with two parameters: resolve
and reject
. resolve
is called when the asynchronous operation is successful, and reject
is called when there's an error. The Promise is resolved with the result of the operation using resolve(result)
and rejected with an error message using reject(error)
.
You can use the then()
method on a Promise to handle the fulfilled state and catch()
method to handle the rejected state. The then()
method takes a callback function that receives the resolved value of the Promise, and the catch()
method takes a callback function that receives the rejection reason.