1 min read

Promises

A Promise is an object representing the eventual completion or failure of an asynchronous operation.

A promise can be in one of three states:

  • pending: The initial state; neither fulfilled nor rejected.
  • fulfilled: The operation completed successfully.
  • rejected: The operation failed.
const myPromise = new Promise((resolve, reject) => {
  // Asynchronous operation here
  setTimeout(() => {
    const success = true;
    if (success) {
      resolve('The operation was successful!');
    } else {
      reject('The operation failed.');
    }
  }, 1000);
});

myPromise
  .then(result => {
    console.log(result); // "The operation was successful!"
  })
  .catch(error => {
    console.error(error); // "The operation failed."
  });