Member-only story
How to Write Callbacks in Node.js
They sound difficult, but let’s take a moment to explain why they’re not
If you’re starting out with Node.js you’ll quickly bump into callbacks. They’re such a popular concept that you’ve already heard about them, but maybe hadn’t thought much about them yet. Well, now you’re here — hi!
Before we define callbacks, we need to understand why they even exist. They exist because of Node’s asynchronous nature. What everybody knows about asynchronous programming is that it’s “better” but “harder”.
OK, That Last Sentence is Slightly Over-Simplistic
Let’s dive in a little deeper and compare code written in a synchronous fashion with its asynchronous counterpart.
What you’ll notice right away is that the asynchronous version is…ugly. It does look like we’re making things unnecessarily complex for little gain, so let’s talk about the gains right away, before you decide to pack JS in and go back to PHP!