What is a Promise | JavaScript

What is a Promise | JavaScript

A Promise is an object that represents an eventual outcome (success or failure) of an asynchronous operation and its resulting value. A promise is basically a placeholder for a value (outcome of operation) or an error (reason for failure) that we will receive at some point in the future, but we don't know exactly when.

Possible Statuses

  • pending - initial state or in progress
  • resolved - an asynchronous operation had completed successfully and resulted in a value
  • rejected - an asynchronous operation had failed and resulted in an error object

Promises

  • settled promise - a promise in the resolved or rejected state
  • chaining promises - asynchronous operations happening one after another, used when each next operation depends on the value from the previous asynchronous operation.
    Example: We can only put the clean clothes (resolved value) to the dryer (promise #2) after washer (promise #1) had completed its cleaning cycle
  • concurrency - multiple operations happening at the same time, used when several asynchronous actions are independent from each other.
    Example: We can have dryer (promise #1), microwave (promise #2) and printer (promise #3) work at the same time as long as we have enough power (threads) to run all simultaneously
  • .then() - Promise method that returns a Promise. This method can take up to two callback functions as its arguments - one to handle success (resolved promise) and one to handle failure (rejected promise).
  • .catch() - Promise method that returns a Promise. This method takes in one callback function as its argument and only handles failure (rejected promise).
  • .finally() - Promise method that returns a Promise. This method takes in one callback function as its argument and runs once the Promise is settled (either resolved or rejected).
Promise Visualization

Creating a Promise in JavaScript

const printerFunction = (resolve, reject) => {
  let printed = true; // change to `false` to trigger `reject()`
  if (printed) {
    resolve('📃'); // 📃 resolved value
  } else {
    reject('⚠️'); // ⚠️ rejection reason
  }
}
const printPromise = new Promise(printerFunction);

Consuming a Promise

const handleSuccess = (resolvedValue) => {
  console.log(`Yay! Let's put ${resolvedValue} in the folder 📁!`);
}

const handleFailure = (rejectionReason) => {
  console.log(`Oh no! There was an error: ${rejectionReason}! Let's fix it ⚒️!`);
}

const makePrintCompleteSound = () => {
  console.log('Beep 🎵!')
}

printPromise
  .then(handleSuccess)
  .catch(handleFailure)
  .finally(makePrintCompleteSound);

Here is what we see in the Console:

// if `printed` is set to `true`
Yay! Let's put 📃 in the folder 📁!
Beep 🎵!


// if `printed` is set to `false`
Oh no! There was an error: ⚠️! Let's fix it ⚒️!
Beep 🎵!
  1. Promise, Promise.prototype.then(), Promise.prototype.catch(), Promise.prototype.finally() by MDN Web Docs
  2. JavaScript Promises by W3Schools
  3. Asynchronous Programming by Marijn Haverbeke, Eloquent JavaScript