How do promises work?
As I mentioned above, a promise has 3 possible states in which a promised will be returned synchronously from an asynchronous function. With a new Promise function, the state begins at “pending” with a result of undefined. The executor will eventually move the promise to having a state of “fulfilled” and a result of the value, or a state of “rejected” with a result of an error. If it is resolved or rejected, the promise is considered settled. Once it is settled, it cannot be resettled and this immutability is an important feature of a settled promise.
When and why to use promises?
- Better error handling
- Improved code readability
- Reduced coupling
- Better definition of control flow of asynchronous logic
Let’s take a look at a simple promise function, showing basic syntax with the use of .then() and .catch():
This will log “Promise was resolved!”, The .then method is invoked when a promise is either resolved or rejected and can take two functions as parameters. In this case we have one function and utilize .catch which will be invoked when a promise is rejected or some error has occurred. The .catch method takes one function as a parameter, a function to handle errors or rejections.
First, a quick overview of what inheritance is: In object-oriented programming languages there exist a mechanism for child objects to inherit attributes from their parents. In order to define these objects and the structures for inheritance, it’s a matter of creating classes that extend to one another. Keep in mind, an object is an instance of a given class, while a class is a definition of attributes and behaviors.
With classical inheritance, instances inherit from classes (a blueprint) and these create sub-class relationships which are known hierarchical class taxonomies. The instances are most often instantiated using constructor functions with the new keyword. Within classical inheritance, objects remain abstractions of real-world things, but we can only refer to these objects through Classes. Classes are essentially a generalization of an object.
How does Prototypal Inheritance Differ from Classical Inheritance?
Within classical inheritance classes are immutable, may or may not support multiple inheritance and may contain interfaces, final classes and abstract classes. Instances inherit from classes, creating sub-class relationships and these instances are typically instantiated using constructor functions
Prototypal inheritance on the other hand, is more flexible than classical inheritance. Prototypes may be mutable or immutable, the object may inherit from multiple prototypes and only contain objects. Instances inherit directly from other objects and are typically instantiated using factory functions. The instances may also be composed of many different objects which allows for an easier selective inheritance.