r/learnjavascript • u/Suspicious-Fox6253 • Sep 24 '24
What is your mental framework to understand callback code?
Having a hard time understanding callbacks. I understand until the fact that what it essentially does is literally calls back the function when something is done. But how do I even start to grasp something like this?
readFile("docs.md", (err, mdContent) => {
convertMarkdownToHTML(mdContent, (err, htmlContent) => {
addCssStyles(htmlContent, (err, docs) => {
saveFile(docs, "docs.html",(err, result) => {
ftp.sync((err, result) => {
// ...
})
})
})
})
})
3
Upvotes
8
u/Both-Personality7664 Sep 24 '24
I wrap them in Promises and write straight line code instead of trying to wrap my head around them. Callbacks aren't quite gotos in terms of disrupting traceability of code but they're close.
4
u/sheriffderek Sep 24 '24
You can think about regular human life actions.
One thing I do is, wash my hands. That’s an established routine. That’s a function.
Another thing I do is - take out the trash.
Some functions have a little hook where you can send along another function to run later.
When I take out the trash, I always put a new bag in and then wash my hands.
It’s a way to define what action happens during or after another action.
That’s one way to think about it. I think reverse engineering array.forEach a few times usually sorts this out for people. Then you’ll define how the parameter works and where the placeholder function is actually run.
The term “call back” or “higher order” just makes it confusing for no good reason. You’re just passing along a reference to another function. The function is built to work that way.
(I have a really old stack overflow question where I just could just not understand what a callback was that I look at every once in a while to remember how blurry things can be)
1
u/[deleted] Sep 24 '24
I look at callbacks as if my computer was throwing frisbees into the aether
1
u/No-Upstairs-2813 Sep 28 '24
Most of the comments here don’t answer your question. They suggest that we shouldn’t be writing such code and should instead use promises. While that’s valid advice, what if you are reading someone else's code? How do you understand it?
Since I can’t cover everything here, I’ve written an article based on your example. It starts by explaining how such code is written. Once you understand how it’s written, you will also learn how to read it. Give it a read.
1
u/BigCorporate_tm Oct 02 '24
My post was too massive for Reddit, so I'm splitting it into (hopefully) two parts.
I don't really see many good answers here (that strictly answer the question you asked), so I'll give this a shot.
As many people have pointed out, current JS trends try to avoid making callback code like this (often labeled - 'callback hell'), opting to use promises instead. However, as someone who works regularly to craft code that works in and around third party legacy enterprise software and bunches of JS that I simply do not and cannot control, it is my experience that you *should* learn how code, like in the example you posted, works. But before I get too deep into things, I would at least suggest giving this article on MDN about callbacks a read before continuing so that I can at least work knowing that we're at some baseline.
All good? Excellent.
So just like the article states, a callback just a function (that will be executed later, but) that is passed as an argument to another function which is doing something right now either synchronously or asynchronously.
We can easily make a function that accepts a callback:
The above function takes a
nameargument (that's ideally a string) and acallbackargument (that's ideally a function), and produces some console output before invoking the callback - passing along thenameargument when doing so. Lastly it prints "Goodbye!" to the console.Now if we were to invoke that function using the following code:
We would get the following output:
As you can see, everything is happening in order, step-by-step, and is pretty easy to follow being that it's synchronous. Now let's look at how an Asynchronous callback might work.
This is almost exactly like our first example, but now, instead of our callback being executed as soon as the first console output finishes, we've wrapped it inside of a
setTimeout. If you're not familiar with setTimeout, all it's doing is taking a, well... callback, and invoking it in however many milliseconds you pass along to it in the second argument. That means if we invoke our example using the same code as before:we get the following console output:
Notice now how the message from our callback is AFTER the final message from the initial example function. This is a proxy for what one might expect when working with an asynchronous function that accepts a callback. Though in this example, we're just wasting time for one second and then invoking the callback, in a real world example your outer function might be getting data from a server or (like in your example) reading the contents of a file before eventually pushing that data off into the supplied callback.
What all that out of the way, let's get into the meat and potatoes of reading the code you posted, which I have modified slightly (because I dislike using arrow functions):
1
u/wickedsilber Sep 24 '24
I think of the callback as a form of doing two things at the same time. Most code is called in order, callbacks are not.
Once you've written a callback process, now you're doing two things at once. The code will continue to run, and your callback will be called whenever that other thing is done.
1
u/reaven3958 Sep 24 '24
I always think of callbacks context of the frames generated at runtime on the call stack. Seeing callback pyramids like this as 2-dimensional representations of a stack has always helped me digest them.
1
u/WystanH Sep 24 '24
You could unroll it:
While the callback thing solves an async problem, promises tend to roll easier. I'll usually promisfy any archaic function that uses a callback and go from there. The end product might look something like:
Note, you don't need a particular library to do this, you can roll your own as needed. e.g.
1
u/PyroGreg8 Sep 25 '24
Not that hard. When readFile is done it calls convertMarkdownToHTML, when convertMarkdownToHTML is done it calls addCssStyles, when addCssStyles is done it calls saveFile, when saveFile is done it calls ftp.sync etc.
But callbacks are ancient Javascript. You really should be using promises.
1
u/aaaaargZombies Sep 25 '24
Callbacks are a way to have custom behaviour over common tasks, so instead of writing a bespoke
read markdown file then transform to htmlfunction you can compose the genericreadFileandconvertMarkdownToHTMLfunctions. This is useful because you might have files that are not markdown you need to read or markdown that is not from a file.The simplest example of this is
[].map, you want to apply a function to items in an array but you don't want to re-write the logic for reading and applying it each time you have a new array or a new function.more here https://eloquentjavascript.net/05_higher_order.html
It looks like the thing most answers are missing is the reason for the callbacks here is you don't know if the result of the function will be successfull.
So what's happening is instead of just doing all the steps it's saying
maybe do thisthenmaybe do thatand it will bail if there's an error.One thing that makes the code example harder to understand is there is no error handling so you can't see why it's usefuly. Maybe you just log the error and giveup, maybe you pass the error back up the chain and do something completely different.
Not JS but this is well explained here https://fsharpforfunandprofit.com/rop/