What are JavaScript promises

JavaScript promises are objects that represent the eventual completion or failure of an asynchronous operation and its resulting value. They are a way to handle asynchronous operations in a more manageable way than traditional callback functions.

A promise can be in one of three states:

  • Pending: The initial state; the operation has not yet completed.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

Promises use the .then() and .catch() methods to handle success and failure cases respectively, making the code cleaner and easier to read.

const myPromise = new Promise((resolve, reject) => { let success = true; // Simulate success if (success) { resolve("Operation succeeded!"); } else { reject("Operation failed!"); } }); myPromise .then(response => console.log(response)) .catch(error => console.log(error));

JavaScript promises asynchronous programming Promise object .then() method .catch() method