In this lesson, you grew the laundry-duty program from the last lesson by one more step, and then handed a callback to a helper that didn’t behave. Both show where callbacks start to break down as a program grows.
Key Points
- Each callback you put inside another is one level deeper. Each result arrives as a callback parameter, which only exists inside its own callback. Here, nesting is how the program keeps all three results in reach, so each step that needs an earlier result goes inside that step’s callback.
- With nested callbacks, every step that waits pushes everything after it one level to the right. Each level repeats the same error check, and the closing brackets pile up at the end, where you have to match each one to its step. Developers call this shape callback hell.
- When you pass a callback to
readFile(), Node calls it once, and always later. With someone else’s code, you trust what it says it does. Kofi says hisreadNote()calls back once, and always later, too. - Once you hand your callback over, the other code decides when it runs, how often, and whether it runs at all. Usually, your code calls functions and stays in charge. Here, Kofi’s code calls yours. Developers call this inversion of control. A helper that breaks its once-and-later rule can call your callback twice, never, or right away:
- Twice: your callback’s work happens twice. If your callback also passed duty on to the next housemate, duty would pass twice and skip Kofi.
- Never: there’s no result and no error. The program ends in silence.
- Right away:
readNote()calls your callback itself, on the same stack, before it returns, so the callback runs before the line after the call. It never goes near the task queue. Not every callback waits. The line after the call then announces a lookup that’s already over: code after the call can’t count on the callback coming later. - Those two problems, nested callbacks and inversion of control, are why JavaScript developers came up with promises. That’s for the next part.
A Helper That Does Both
The video mentioned a helper that waits one time and answers right away the next. Here’s one. This version of Kofi’s readNote() keeps each note it has read in a Map, so it doesn’t have to read the file again: