Ajax and Async Code
Kurt Bauer
Posted on August 20, 2019
What is Ajax and Why?
So first of all, I would like to say that every time I talk about AJAX I can't help but think of Jax, the fighter in Mortal Kombat with the two metal arms...anyone else?
Ajax is a technique for accessing web servers from a web page. It stands for "Asynchronous JavaScript and XML". Yeah, that's a mouthful, so let's take a second to unpack that.
Now, before you start claiming that Ajax is some sort of API or NPM package, you should understand that Ajax is more so a term that describes a model built up of a multitude of technologies, of which the XMLHttpRequest object is the most pivotal.
Those sweet MDN docs for a more technical read
An XMLHttpRequest object, or XHR for short, allows you to interact with servers! Yes, you too can have the powerrrr!
This is where things get super interesting. I know, as if they weren't interesting before right!? So when looking at MDN, the key thing to realize about what XHR allows us to do as developers is this...
"You can retrieve data from a URL
without having to do a full page refresh."
- with love, the MDN gods
When this ability is injected into something like say ReactJS, we're able to update specific pieces of our web apps behind the curtain while the user is provided a seamless experience. The term for this action, of showing our users a stable clean site in one hand while completing our magic trick with the other hand is Asynchronous request.
At this point, we're left with two lingering questions.
- What is the XMLHttpRequest object?
- What does Asynchronous mean?
To create an XHR request, you may have written something like what I have below in the past if you've been in the game longer
const request = new XMLHttpRequest();
Thanks to the progress (and headaches) of other developers, we now have a multitude of libraries or the more commonly used Fetch API that allows use to both read and write more universally understandable requests.
An example of a fetch request to an api would be as follows
More on Fetch at MDN
Although XML has a large part to play, these requests can pull different data types like JSON above.
When we console.log(), our object looks as follows
{ "name": "Luke Skywalker", "height": "172", "mass": "77", "hair_color": "blond", "skin_color": "fair", "eye_color": "blue", "birth_year": "19BBY", "gender": "male", "homeworld": "https://swapi.co/api/planets/1/", "films": [ "https://swapi.co/api/films/2/", "https://swapi.co/api/films/6/", "https://swapi.co/api/films/3/", "https://swapi.co/api/films/1/", "https://swapi.co/api/films/7/" ], "species": [ "https://swapi.co/api/species/1/" ], "vehicles": [ "https://swapi.co/api/vehicles/14/", "https://swapi.co/api/vehicles/30/" ], "starships": [ "https://swapi.co/api/starships/12/", "https://swapi.co/api/starships/22/" ], "created": "2014-12-09T13:50:51.644000Z", "edited": "2014-12-20T21:17:56.891000Z",
Asynchronous basically means that, multiple things can occur at the same time. If you click a button to see more star wars facts, your JavaScript page doesn't have to stop what it's doing, it can keep showing the user a cool interactive site, and in the background start requesting data from an API endpoint.
Most browsers today run on a JavaScript based engine, and JavaScript itself is used to running synchronously, meaning it must wait for one task to complete before moving on to the other, in the order the tasks were coded to be created.
Usually the JS engine is not the only engine that's running. We have items like the rendering engine, or as we've seen, elements that request data through an HTTP request. So although the JS code is running in a synchronous way, there are other pieces that are doing work asynchronously.
JS has an execution stack, built of execution contexts that are created and run in the order that they were created. Once complete, each execution context drops off.
Parallel to this is the Event Queue, made up of events and notifications of events that are occurring, like button click for example.
BUT, here's a big but, JS only starts attending to the event queue AFTER the execution-stack is emptied.
If an event causes a function to be created and executed, an execution context is created when we reach that event, like handling an HTTP Request as we've seen above with our fetch. And so, it is placed in the call-stack to be run. And that's it!
JS is continuously running an Event Loop, to keep checking periodically if there is something else to do, this is what allows JavaScript to go back and take a look at events after it's initial execution stack is exhausted.
Events are looked at Synchronously by JS, but the browser will place them into the event queue in an Async manner. JS can continue to load all the files and functions you've written out in your app, while specific triggers and events can be thrown in independent of the JS Engine, to a certain degree.
Posted on August 20, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.