Credit to Simon Haddad for being a key part of preparing this lecture
Javascript, unlike languages like Python or C, has asynchronicity built in by default.
That means things tend to be async by default, and we have to work around this, like we did when we learned about callbacks.
Promises, like callbacks, assist us to manage delayed completion of blocking code (file I/O, network I/O, etc)
Promises provide us with the same problem-solving environment as a callback pattern, but with substantially more powerful capabilities and a syntax capable of cleaner code.
Let's do a direct comparison of our callback and promise code.
Type | Callback | Promise |
---|---|---|
Linear | chapters-callback-linear.js | chapters-promises-linear.js |
Nested | chapters-callback-nested.js | chapters-promises-nested.js |
Let's learn about how to turn a fileRead standard callback function into a promise. This involves understanding the structure of a promise.
Constructor:
.then:
.catch:
Let's learn about how to turn a fileRead standard callback function into a promise. This involves understanding the structure of a promise.
A promise has a few possible states:
Promises can be chained together to enforce order of processing and ensure clear and concise syntax. This is shown in chapters-promises-nested-clean.js
Branching promises allow you to control what is processed concurrently and what is processed linearly
Mostly error handling is quite straightforward, but there are a few extra details worth considering.
The Promise class has some utilities for easy orchestration