Basic overview on JavaScript Promise

Published on Mar 10, 2021 · 2 min read

A promise represents a value that is unknown now that may become known in the future, in other words an asynchronous value. Think of it like a ride hailing app. When you request a ride, the driver makes a promise to pick you up. While you are waiting, the ride is pending. In the future if all goes according to the plan, the driver will resolve to pick you up then take you somewhere at which point your ride has been fulfilled. But, in some cases the driver might reject your ride in which case you will need to catch one somewhere else. Either way the original request is now finally settled.
As a developer, you might want to create a promise to represent an asynchronous value. But, more often than that, you will be consuming promises to use the result of an asynchronous operation in your code.
// create
const ride = new Promise((resolve, reject) => {
  if (arrived) {
    resolve('driver arrived 🚗');
  } else {
    reject('driver bailed 😢');
  }
});

// consume
ride
  .then((value) => {
    console.log(value);
  })
  .catch((error) => {
    console.log(error);
  })
  .finally(() => {
    console.log('all settled');
  });
When constructed, a promise starts off in a pending state. It is your job to define a callback function called an executor that defines when to resolve or reject the promise. This is where you would kick off your asynchronous work. On the other side, the consumer of the promise calls its then method. It is waiting for the asynchronous value to be fulfilled. When that happens, it will execute the function – the argument on .then method – with the value as its argument. We fulfill the promise by calling resolve. But, there is always the possibility of an exception. In that case we can reject the promise and send the error back down to the consumer which can use the catch method with an entirely different function for handling exceptions. Also, if you just want to run some codes no matter what, you can use finally to handle both possibilities. All of these methods return promises which means they can be chained together to handle multiple asynchronous operations in a row.
promise
  .then(() => {})
  .then(() => {})
  .then(() => {})
  .catch(() => {})

Articles you might like