Is JavaScript synchronous or asynchronous? What the hell is a promise?
We, the people, like structure. We like categories and descriptions and putting everything we know into tidy little boxes. This is why I found JavaScript so confusing at first. Is it a scripting or a programming language? Is it used on the front or back end? The wonderful (read: awful) thing about JavaScript is that, most of the time, it’s a little bit of both. JavaScript has evolved so much over the years that it’s slippery to categorize. Today, I’m just going to dive into whether JavaScript is synchronous or asynchronous, and what workflow looks like under the hood.
JavaScript is Synchronous
Spoiler: at its base, JavaScript is a synchronous, blocking, single-threaded language. That just means that only one operation can be in progress at a time. That’s not the entire story, though!
What if you have to make an expensive database request? You don’t want to be twiddling your thumbs while ol’ PG and Postgres grab those 800 songs you need for your music library. Synchronous code makes a programmer’s life very difficult, so the JavaScript community developed some great workarounds. When you hear folks say that JavaScript is an asynchronous language, what they mean is that you can manipulate JavaScript to behave in an asynchronous way. It’s not baked in, but it’s possible! Here are a few ways to make that happen:
Asynchronous Callbacks
The earliest and most straightforward solution to being stuck in the synchronous world was asynchronous callbacks (think setTimeout()). Let’s use a database request as an example: asynchronous callbacks allow you to invoke a callback function which sends a database request (and any other nested callbacks) off to your app, where it waits for the response from the database, freeing up the rest of your code to continue running.