The Story of Asynchronous JavaScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
it's safe to say that javascript has matured over the years how we write javascript applications today is drastically different than how we did just a decade ago nowhere is this more prominent than when it comes to fetching data from external apis to truly understand how we got to where we are today let's take a trip back to the past seat belts everyone please let this be a normal field trip in the beginning of the web there were just documents with links between them cyberspace set free hello virtual reality when a browser made a request to the server for a particular page the server would find the html file stored on its hard disk and set it back to the browser not long after that server started pre-processing the html before it was sent to the client every time a browser would request a page based on the user's cookies or authentication headers the server would generate the html on the fly for that specific user this allowed companies to start creating websites that allowed you to do more than just read documents deliveries but there was still something missing yes pages were being dynamically created on the server but the end result the user got was still a static experience not only that but this process meant that every change in a page's content required a full page refresh then in 1999 everything changed with one invention [Music] oh no not that when i think back hard is because we couldn't build great applications on the web technologies of the time we could build information resources you could read things and do things and so forth but you couldn't build web applications that were at the scale and power of the then existing desktop applications there was a technology built in 2003 2004 which came it was called asynchronous javascript in xml abbreviated as ajax which built the first interesting web apps gmail for example was either the first or one of the early first ajax applications and all of a sudden people said you know this web thing is actually kind of useful i can write some pretty interesting applications they can update themselves and so forth and so on ajax changed the game because it allowed browsers to send and receive data from the server without needing to reload the page this one change ushered in the next era of rich dynamically generated web apps so what did this exactly look like so basic implementation using low level ajax you got a lot of code in there right so you create a new object and you open and then you assign your own ready state change check the ready state you check the status code and then you try to parse the response you go and you pull in the status node and you want to make sure that it's also okay and then you process the data that's in the data node into some format that everything can understand because you don't want it in xml then you pass that into handle success and if any of that doesn't work then you want to call handle failure though it was a little weird the xml http request api worked because javascript treats functions just like any other value and that you can assign them to variables another benefit of being treated like any other value is that you can pass functions as arguments to other functions which is used in just about every javascript library you'll use nowadays when you do this the function you're passing as an argument is called a callback function in general there are two popular use cases for callbacks the first and what you see in the map example is a nice abstraction over transforming one value into another the second and what we see in the jquery and react examples is delaying execution of a function until a particular time it's the second use case that is the more interesting one instead of delaying execution of a function until a user clicks a button what if we delay execution of a function until we receive data from an external api in fact for years this was the pattern we used for fetching external data we just saw this with the raw xml http request api and we see it again with jquery's abstraction over it called get json it's as if we said hey jquery here are two functions if at some point in the future the request succeeds invoke handle success passing it the newly fetched data if it doesn't invoke handle failure passing it the error that occurred this was a perfect use case for callbacks and it was great until it wasn't take this code for example here we have a callback nested inside of a callback and if we were using jquery nested inside of another callback this became so prevalent that it even had two nicknames callback hell and the pyramid of doom the problem is with each layer of nesting it becomes more difficult to understand what's going on because it forces you out of your natural way of thinking one common approach to minimizing the effects of callback hell was to modularize your code but is this objectively better probably not we've kind of just spread the mess around and called it more readable the fundamental problem still exists and this isn't the only problem another problem here has to do with inversion of control when you write a callback you're essentially inverting the control of your program over to another program it's entirely possible that this third party library could break how they interact with your callback so how do we fix these problems well we can look at a real life example for some hints the service was really beautiful have you ever been to a busy restaurant without a reservation when this happens the restaurant needs a way to get back in contact with you when a table opens up historically they take your name and yell it when the table was ready this worked unless the restaurant was too crowded then they decided to start getting your phone number and text you once a table opened up this allowed you to be out of yelling range but more importantly it allowed them to target your phone with ads whenever they wanted sound familiar well it should or maybe it shouldn't it's an analogy for callbacks giving your number to a restaurant is just like giving a callback function to a third party api once you give it up you've lost all control of how it's used thankfully there is another solution that exists instead of taking your name or number they give you this device when the device starts buzzing your table is ready you can still do whatever you like as you're waiting for your table but with this you don't have to give up anything in fact they have to give you something there's no inversion of control the buzzer will always be in one of three states pending which is the default initial state when you receive it fulfilled which is the state when it's flashing and your table is ready or rejected when something goes wrong like maybe the restaurant is about to close the important thing to remember is that you the receiver of the buzzer have all the control regardless of which state it's in you get to choose how to respond so what does this have to do with async javascript well if giving the restaurant your number is like giving them a callback function receiving this little buzzy thing is like receiving what's called a promise exactly like the buzzer a promise can be in one of three states unlike the buzzer instead of these states representing the status of a table at a restaurant they represent the status of an asynchronous request if it was successful the promise will change to a status of fulfilled and if it failed the promise will change to a status of rejected the way you create a promise is by creating a new instance of promise next you need to be able to change the status of a promise when you create a promise the promise constructor function takes in a single argument a function this function is going to be past two arguments resolve and reject resolve allows you to change the status of a promise to fulfilled and reject allows you to change the status of a promise to reject it now the question is how do you listen for when the status of a promise changes well a promise is really just a javascript object that has two methods on it then and catch here's the key when the status of a promise changes to fulfilled the function that was passed to then will get invoked when the status of a promise changes to rejected the function that was passed to catch will get invoked so now that you know your way around the promise api let's do some refactoring from our code from earlier notice that we no longer need to pass on success and unfailure arguments since we're no longer inverting control instead we can use the promises resolve and reject functions now that get user and get weather return promises we can update where we invoke those functions our new code is better but there are still some improvements we can make specifically around what's called chaining what's cool about promises is that both then and catch will return a new promise that seems like a small detail but it's important because it means that promises can be chained this solves one of the downfalls of callbacks specifically that callbacks force you out of your natural way of thinking however it's not without its tradeoffs either the biggest problem with chaining has to do with getting state down the chain in order to invoke handle success we need both the weather and the user unfortunately with how we've currently implemented it user gets lost inside of our getweather function so we can either create a temporary variable in the parent scope to hold the user or we can pass along the user from inside of our gitweather function when we resolve either way this is a step in the right direction from our original callback problem in fact at this point we can even get rid of jquery's get json altogether by refactoring to use the native fetch api instead which also returns a promise so this is great but can we do even better the best api is often no api and as we saw chaining promises isn't without its trade-offs either let's assume that we were on the tc39 committee and had all the power to add new features to the javascript language [Music] what steps could we take to improve this code well one issue that we did run into was that we needed to thread the data from the first async request all the way to the end but what if we just wrote our asynchronous code the same way in which we write our synchronous code if we did this entire problem would just go away sadly this obviously won't work since user and weather would both just be promises as is this code would be really tricky to make work we'd have to somehow teach the javascript engine to know the difference between asynchronous function locations and regular synchronous function invocations on the fly let's add a few keywords to our code to make it easier on the engine first let's add a keyword to the main function itself this concludes the engine into the fact that inside of this function we're going to have some asynchronous function invocations cool now let's add another keyword to let the engine know exactly when a function being invoked is an asynchronous function and it's going to return a promise pretty nice we've invented a reasonable way to have our asynchronous code look and behave as if it were synchronous and as you've probably guessed by now this feature is already part of javascript and it's called async await there's just one more thing we didn't talk about and that's error handling in our original code we had a way to catch any errors using catch when we switch to async await we remove that code with async await the most common approach is to wrap your code in a try catch block to be able to catch the error that occurs so whether you're using callbacks promises or async await getting comfortable with data fetching is critical for any javascript developer and understanding how we got here gives you the historical context to do just that interactive appetite searching for a website a window to the world got to get online take a spin now you're in with the techno set you're going surfing on the internet
Info
Channel: uidotdev
Views: 147,052
Rating: undefined out of 5
Keywords:
Id: rivBfgaEyWQ
Channel Id: undefined
Length: 10min 20sec (620 seconds)
Published: Mon Feb 21 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.