JAVASCRIPT

Promises


Promises in JavaScript are objects representing the eventual completion or failure of an asynchronous operation. They are used to handle asynchronous operations such as fetching data from a server, reading files, or executing code after a timeout.

 

Promises have three states:

  • Pending: Initial state of a promise. The asynchronous operation has not yet completed or failed.
  • Fulfilled (resolved): The asynchronous operation has completed successfully, and the promise returns a value.
  • Rejected: The asynchronous operation has failed, and the promise returns a reason for the failure.

Promises can be created using the Promise constructor. The constructor takes a function with two parameters: resolve and reject. Inside this function, you perform the asynchronous operation, and once it is completed, you call resolve with the result or reject with an error if it fails.

 

Example:


const myPromise = new Promise((resolve, reject) => {
// fetching data
setTimeout(() => {
    const data = { message: "Promise resolved" };
    resolve(data); // Fulfill the promise with data
}, 1000);
});

// Consuming the promise using then() and catch()
myPromise
.then((result) => {
    console.log(result); // Output: { message: "Promise resolved" }
})
.catch((error) => {
    console.error(error); // Handle error if promise is rejected
});