- Async Programming
- Consuming and creating promises
- Async Await
What problem they solve?
To avoid undefined responses when dealign with external API content retrieved via AJAX calls, we can use Promises as a technique that allow us to ensure we have the data before we try to use it. Callback pyramid of Doom, many levels of nesting indentation of functions, a.k.a. "Callback hell".
- The "bad" part is that the code becomes dirty and is error prone.
- Error handling , the pyramid of doom can make the code even messier, adding more indentation.
- Hard to read
Promises allow us to execute code without massive nesting callbacks.
Promises definition according to Mozilla MDN: Object that represents the eventual completion (or failure) of an async operation, and its value.
Promises have 3 states:
- Pending state -> while the promise is happening is pending, until it is...
- Fullfied state -> returns a single value grabbed from for example an API.
- Rejected state -> the promise fails so it returns a reason why it was rejected similar to a Catch function in a try catch block.
- Other terms: Setteld and Resolved, both refer to the same state - either Fullfied or Rejected state, it is no longer pending.
Promises in "real life"
We can get data from an API, to see how this works in real life.