In the last lesson, we learned how to use callbacks to handle asynchronous tasks. Now, let us put our knowledge into action with an exercise inspired by the Apollo 11 mission.
To successfully send astronauts to the Moon, several critical steps must be completed in a specific sequence.
- 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 outcome of the previous one. For instance, without knowing the distance to the Moon, we can't determine how long the journey will take. Let us write code to handle these steps using callbacks.
We will create a function for each step. Each function will simulate a time delay using setTimeout
and pass the necessary data to the next step using a callback.
calculateDistanceToMoon
- calculates the distance to the Moon
The Pyramid of Doom
Now, we will coordinate these steps to complete the mission.
The code works as expected, and the steps are completed in the correct order. However, the structure is deeply nested, making the code challenging to read and manage.
Each step is embedded inside the callback of the previous step, creating a pyramid shape. Adding a new step or changing the sequence requires navigating through multiple levels of callbacks. Moreover, handling errors becomes complex and scattered.
This issue is known as callback hell, where nested callbacks make the code messy and difficult to maintain.
In the next lesson, we will check out how promises can help us handle asynchronous tasks more effectively, allowing us to write cleaner, more readable, and maintainable code.