JavaScript Promises 101

JavaScript Promises 101

ยท

2 min read

Hey there! Are you new to JavaScript? Well, this post is right for you! Mastering promises is a must if you want to become a JavaScript developer!

A Promise represents a value that's unknown now that may become known in the future; in other words an asynchronous value. alt text

A Promise is always in one of these states:

  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation was completed successfully.
  • rejected: meaning that the operation failed.

Now, let's imagine you're hungry (I am now actually) and you're about to order food using a delivery app. You open the app. You find what you want and click order. At that moment, the restaurant/app makes a Promise that they will deliver you food. While you're waiting, the delivery is pending. In the future, if everything goes according to plan the restaurant/app will resolve to deliver you food at which point your order has been fulfilled. But in some cases, the restaurant/app might reject your order in which case you'll have to order something else. Either way, the original request is finally settled.

More technical explanation

Now, let's explain it in a more technical language. As a developer, you create a Promise to represent an asynchronous value. But, what you'll actually do more often is consuming promises to use the result of an asynchronous operation in your code.

Let's create a Promise.

const food = new Promise((resolve, reject) => {
                               //โ˜๏ธ*
  if (delivered) {
    resolve("food delivered ๐Ÿฅ˜");
    // resolve fulfills promise with passed value
  } else {
    reject("you're still starving... ๐Ÿ˜ญ");
    // reject triggers when operation fails
  }
});

*๐Ÿ‘‰ executor, f-on that resolves a value or rejects (error)

Now let's consume the Promise.

food
  .then(value => {
    console.log(value); // food delivered ๐Ÿฅ˜
  })
  .catch(error => {
    console.log(error); // you're still starving... ๐Ÿ˜ญ
  })
  .finally(() => {
    console.log("all settled!");
  });

then is a function that handles fulfilment. catch handles rejection; catches the error. And finally, finally is there if you want to run some code no matter what.


I hope this helped you get the basic knowledge, an overview of JavaScript Promises :)

As always, any feedback is greatly appreciated!

Have a great one, Dalibor

ย