JavaScript Promises Explained

JavaScript Promises Explained

JavaScript promises is a relatively new feature that has been introduced in ECMAScript 2015 (ES6).

Since then promises have become popular and used widely by developers.

The reason for this popularity is mainly because promises offer a more robust and readable approach when implementing asynchronous operations compared to callbacks or event listeners.

If you’re fresh to this concept, by the end of this article you’ll be ready to implement promises into your code.

What is a Promise?

A promise is like a placeholder for an asynchronous task that will be completed in the future.

When you define a promise object, instead of returning a value straight away, you return a promise. Then when an asynchronous task is completed, the promise is either fulfilled, meaning the operation was successful, or the promise is rejected, meaning the operation was unsuccessful.

In short, a promise can only be in one of three states:

• Pending: Initial state, the operation is not yet completed.

• Fulfilled: The operation was completed successfully.

• Rejected: The operation failed.

The states are irreversible. Once a promise is fulfilled or rejected, it cannot be changed.

Creating a Promise

So now, after we know what a promise means, let’s write some code.

To create a promise, we will be using a Promise constructor with two parameters: resolve and reject.

Then inside this constructor, we will return either the fulfilled state or a rejected state:

In this case, the reject state with an 'Operation failed' message will be returned.

Consuming a Promise

After the promise finally returns some value, you usually want to use this value somehow.

To act upon a promise resolution or rejection, you can use .then() and .catch() methods:

Because our promise in the last example was rejected, here catch method is called with an error message logged out in our console.

Chaining Promises

The really useful feature of promises is their ability to be chained:

Only when the previous .then() method is executed, the next one starts, and the value is passed down to each.

As in the promise consumption example, here you should include .catch() method as well, to catch any errors in the promise chain.