Understanding Asynchronous JavaScript

Image for post
Image for post

Transitioning from Ruby to JavaScript takes some getting use to. In Ruby, programs are written, and run, synchronously. Here’s an example of synchronous code in Ruby:

def my_function
puts 'Hello World'
def another_function
puts 'forgot the "!"'
my_function #=> Hello World
another_function #=> forgot the "!"

In this example, each function is called one after the other, and until the first function call puts ‘Hello World’, the second function will not execute its puts statement.

However, in JavaScript, things become a bit more complexed when asynchronicity is involved. Here’s another example of asynchronous code in JavaScript:

function fetchData(url) {
.then(resp => resp.json())
function myFunc() {
console.log('Hello World!')
LOG: //=> Hello World!
LOG: //=> *fetched data

In this example, although fetchData was called first, myFunc logged to the console before it. So what happened? To better understand, it’s important to note that the fetchData function involves making a HTTP request via fetch, which belongs to the JavaScript Web APIs and exists outside of the JavaScript engine. To illustrate in steps involved in these two function calls:

Within those two simple function calls, this entire process was being carried out. The asynchronous nature of the fetchData(someURL) call allowed for the execution to continue and not come to a halt until the data was returned from the HTTP request. Knowing how this process is carried out under the hood is useful when coordinating function calls, especially when the returned value of one is depended on by another. And just as a helpful reminder, fetch, DOM events (event listeners), XMLHttpRequest, setTimeout and a few others all execute asynchronously.

Flatiron School alumni and Full Stack web developer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store