I’ve had a hard time trying to learn promises in Javascript. Here is why.
What do I mean by learn
When I learn something, I learn to understand, not simply to use. In this case, it means understanding the syntax, but also the flow of data and function calls.
Why was it difficult
Compared to traditional programming, I found that Promises where difficult because:
- you manipulate callbacks (resolve() and reject()) through an object (using .then and .catch) - this is in contrast with traditional callbacks passed as arguments to a function.
- because we often use arrow functions to define the callbacks, their arguments to use must follow the way the promise
resolve
andreject
defined first. So the callback impose the arguments, not the function definition. So for exemple when defining a promise with :resolve('test')
, the callback must expect a string input. - using .then returns a promise. This is what allows chaining.
- when chaining, if you need data used in a previous .then, you need to return it in resolve().
Teaching material I used
Thanks to the following videos for helping me understand :
- https://youtu.be/gB-OmN1egV8
- this video is confusing about the flow of data because it uses getJSON in the promises, which uses a callback internally and hides away the returned objects.
- https://youtu.be/DHvZLI7Db8E
I also watched the following videos :
- https://youtu.be/vn3tm0quoqE
- https://youtu.be/PoRJizFvM7s But they didn’t help me understand promises, because they are about syntax, and not the flow of function calls and exchange of data. I’m not saying they are bad, just that they didn’t help ME understand how javascript promises work.