This article explains what Promise chaining is and how it works. You can find a basic explanation of what a Promise is in one of my previous short and easy to follow articles. If you’re new to the topic, then I recommend you read it first.

Although Promises and Promise chaining may seem complex and difficult to understand, they are here to make our life easier. As Marijn Haverbeke wrote in his book “Eloquent JavaScript” — the art of programming is the skill of controlling complexity. Promises were added to JavaScript language to help manage the complexity of code.

What makes Promises challenging in my opinion is all the stuff that is happening in the background and which is not that obvious after just reading the code. This is why understanding basic concepts is so important.

“The art of programming is the skill of controlling complexity” — Marijn Haverbeke

A Little Bit of Promise Theory

A Promise is an object with many properties and methods. It can be in one of three states:

  • pending: initial state, neither fulfilled nor rejected
  • [[PromiseStatus]]: “pending
  • fulfilled: operation completed successfully
  • [[PromiseStatus]]: “resolved
  • rejected: operation failed
  • [[PromiseStatus]]: “rejected

We create an instance of a Promise using its constructor function Promise(). When a Promise object is first created, it is in a pending state. The constructor function takes one argument — an executor function (resolver). The executor function initiates an asynchronous task and defines conditions for fulfilling and rejecting the Promise.

We can attach success and error handlers to a promise using then() method. We can do that before or after the Promise is settled (i.e. fulfilled or rejected). If a handler is attached to a resolved Promise, then it is called as soon as possible.

Success and error handlers always return Promises. If we return a value from a handler, then the handler will return automatically generated resolved Promise with that value as its value. These automatically generated resolved Promises can be replaced with new pending Promises defined by a developer. To do that you simply return a new Promise from the handler.

#promises #javascript

JavaScript Promise Chaining — Basics
1.05 GEEK