We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Promises

Click to play video

A Promise in JavaScript is very similar to a promise to your friend. It's just a commitment for the future. For example, I promise to explain promises to you. This promise to you has 2 potential outcomes:

  • It's fulfilled, meaning I eventually explained
  • It's rejected, meaning I failed to explain

The Promise Object represents the eventual fulfillment or rejection of a promise. In the meantime, while we're waiting for the promise to be fulfilled, our code continues executing. Promises are the most popular modern way to write asynchronous code in JavaScript.

Creating a Promise

Here's a promise that, based on random number generation, will resolve and return the string "resolved!" or reject and return the string "rejected!" after 1 second:

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    if (getRandomBool()) {
      resolve("resolved!");
    } else {
      reject("rejected!");
    }
  }, 1000);
});

function getRandomBool() {
  return Math.random() < 0.5;
}

In the new Promise((resolve, reject) => { ... }) constructor, resolve and reject are functions provided by JavaScript that you call to either successfully complete the promise (resolve) or signal that it failed (reject)

Working With Promises

Now that we've created a promise, how do we use it?

The Promise object has .then and .catch methods. Think of .then as the expected follow-up to a promise, and .catch as the "something went wrong" follow-up.

  • If a promise resolves, its .then method will execute.
  • If the promise rejects its .catch method will execute.
promise
  .then((message) => {
    console.log(`The promise finally ${message}`);
  })
  .catch((message) => {
    console.log(`The promise finally ${message}`);
  });

// if the promise (from the first example) resolves, the output will be:
// The promise finally resolved!

// if the promise rejects, the output will be:
// The promise finally rejected!

Assignment

In Textio, sending messages is an asynchronous process that sometimes takes time to update its status. We'll simulate this by creating a function that returns a Promise which resolves or rejects after a half-second delay.

If you run the starting code as is, it will never exit because the promise doesn't resolve or reject. Just click cancel if that happens.

Complete the updateMessageStatus function that takes three parameters:

  • messageId – a string representing the message ID.
  • currentStatus – a string representing the current status of the message (e.g., "Sending").
  • isDelivered – a boolean indicating whether the message has been delivered.

It should return a Promise immediately that, after a half-second delay, does the following:

Textio Message MESSAGEID has been delivered successfully.
Textio Message MESSAGEID is still sending and cannot be marked as delivered.
Textio Message MESSAGEID status updated to CURRENTSTATUS.

Where:

  • MESSAGEID is replaced with the value of the messageId parameter.
  • CURRENTSTATUS is replaced with the value of the currentStatus parameter.