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 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.
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
});