Revealing constructor
The revealing constructor pattern is a relatively new pattern that is gaining traction in the Node.js community and in JavaScript, especially because it's used within some core libraries such as Promise
.
We have already implicitly seen this pattern in
Chapter 4, Asynchronous Control Flow Patterns with ES2015 and Beyond, while exploring promises, but let's get back to it and analyze the Promise
constructor to embrace it in greater detail:
const promise = new Promise(function (resolve, reject) { // ... });
As you can see, Promise
accepts a function as a constructor argument, which is called the executor function. This function is called by the internal implementation of the Promise
constructor and it is used to allow the constructing code to manipulate only a limited part of the internal state of the promise under construction. In other words, it serves as a mechanism to expose the resolve
and reject
functions so that they can be invoked to change the...