Intro:
This page demonstrates the difference between JavaScript Callbacks and Promises. In both scenarios, we attempt to fetch a "Flupe" user but first we must get past an authentication step. We use JavaScript's setTimeout() to simulate the service calls being made to a fictitious backend/server.
We also make use of the new ES6 JavaScript syntax. And we have to because ES5 doesn't support Promises.
NOTE: In the Callback scenario, neither the authentication or fetch user steps can fail, however, the authentication step can return false signifying that we're not authenticated.
In the case of the Promise scenario, authentication can also return both true or false but we've added the more realistic conditions where both the authentication and fetch service calls can potentially fail. This example attempts to illustrate how error handling should be implemented with Promises when Promise A (authenticate) calls Promise B (fetch user).
A key point to understand here is that the authentication step can return false but this does not imply that the Promise failed. Failure only happens when the service call blows up on the server end.
I've built this example with the following probabilities:
- Service call (getAuthenticationStatus() and fetchUser()) success rate: ~75% chance
- We're authenticated: ~66.3% chance
Finally, I've documented the hell out of this code so that you can learn from it. It's meant to be a teaching example because Promises can be hard to understand and use correctly. My work was based on Maximilian Schwarzmüller's Tutorial. Thank you, Max. You rock!
Check out the promises-demo.js file.
Run Example:
Instructions:
Press Button 1 on the left
to run the Callback scenario or
Button 2 to run the
Promises scenario.
|
|