In the previous lesson, we learned about promises and how they provide a cleaner way to handle asynchronous operations compared to callbacks. Let us revisit the Apollo 11 mission and refactor our code to use promises, eliminating the pyramid shape caused by nested callbacks.
To recall, the mission involves these sequential steps.
- Calculate the distance to the Moon.
- Determine the speed of the rocket.
- Calculate the time required to reach the Moon.
- Verify the trajectory.
- Initiate the launch.
Each step depends on the result of the previous one. Using promises, we can chain these operations, resulting in cleaner, more maintainable code.
We will refactor each function to return a promise.
calculateDistanceToMoon
- calculates the distance to the Moon
determineRocketSpeed
- determines the speed of the rocket
calculateTimeToReachMoon
- calculates the time required to reach the Moon
verifyTrajectory
- verifies the rocket's trajectory
initiateLaunch
- initiates the rocket launch
Now, instead of nesting callbacks, we can chain these promise-based functions using .then()
. Each function handles its specific task and passes the result to the next.
The code now has a flat structure with each step at the same logical level, removing the deeply nested pyramid shape that makes callback-based code hard to read.
With promises, errors can be caught in a single .catch()
block at the end of the chain.
Adding new steps to the sequence is straightforward. We can simply append another .then()
block to the chain.
Check out the code snippet below to see a comparison of the callback-based code from the previous lesson and the promise-based code from this lesson.
As you can see by using promises, we solve callback hell while maintaining the sequential flow. The code becomes cleaner, more readable, and easier to maintain.