JavaScript: The Hard Parts, v3

Asynchronous Code Overview

Will Sentance
Codesmith
JavaScript: The Hard Parts, v3

Lesson Description

The "Asynchronous Code Overview" Lesson is part of the full, JavaScript: The Hard Parts, v3 course featured in this preview video. Here's what you'd learn in this lesson:

Will explains the single-threaded nature of JavaScript would cause delays when waiting for tasks like fetching data from a server. To address this, JavaScript relies on external features provided by the web browser or Node environment, such as timers, network requests, and the DOM, which run outside the main JavaScript thread. These external features allow asynchronous operations without blocking the single JavaScript thread, making the language powerful despite its single-threaded nature.

Preview

Transcript from the "Asynchronous Code Overview" Lesson

[00:00:00]
>> Will Sentance: In fact, I had to use it to go inside and multiply by 2 before I could get the return value and assign it to output. I did not hit multiply by 2 call and then go, ah, do some more work while we're waiting on multiply by 2. You can probably see where I'm going with this. That's maybe a problem. Asynchronicity is the backbone of modern web development in JavaScript, and yet we've just seen it is single-threaded, one command runs at a time, it is run and executed synchronously, each line is run in order the code appears.

[00:00:32]
We didn't jump down to other bits before we did something else. It's super predictable. But what if we therefore had a task accessing TikTok? I chose a really who knows that by the time this goes live, this may no longer be accessing TikTok's server, so that's not on our computer, it's somewhere else, to get new video links, that could take a long time. In the land of computing, that could take vastly longer than our entire application takes to execute its code.

[00:01:02]
Maybe it takes 300 milliseconds, maybe it takes 100 milliseconds, but it's going to take time to go, which is remarkably short, of course, given it's speaking to a server in West Virginia, potentially, or wherever Oracle has put the. Anyway, who knows? But we also don't want to not do, we want to go and do that work because we want to work on that data, maybe, for example, run some code displaying those videos once we have the data back.

[00:01:31]
Challenge, we want to wait for the video links that we could then store back in JavaScript, and then run some code on, but that would mean no code could run in the meantime. Let's have a look at some sort of dummy codes and kind of pretend code. Slow function blocks further code running because JavaScript is a single thread. Have a look at this code here. We're going to have our function get videos, it's going to head off to TikTok and get some videos from me, I suppose, maybe.

[00:01:59]
It might take us, you know, some time, 350 milliseconds, while that request is sent to TikTok. When the result comes back, we want to run a function display videos on that data. But we do need to wait for the videos to display them. But my lovely console log says, I wanna run. Can it run in between? No, single thread? Well, what if we try to delay our function directly? Using setTimeout. So we declare a function print hello, we're then going to use this built-in function setTimeout, that is going to allow us to delay by 1000 milliseconds the running of our print hello function, and we want to manually wait for our 1000 milliseconds to pass, we have to do that, people, presumably, I mean, presumably we're having to do the counting, maybe some way in JavaScript, but I don't know, like some sort of count in JavaScript to wait time, maybe, we know how long a loop takes and we're going to wait that time.

[00:03:00]
With that in mind, what will the console logs in our code here, what order will they log in, we have our declaring print hello, we're then setting a timeout that when it eventually finishes running, we'll print hello, the console log hello inside print hello, and then we've got our console log me first. I assume. Well, let's see, what do we think? Matt, you're up. Matt, stop testing. Matt, what order do we think here?

[00:03:29]
OK, what order do you know these are actually going to, what order does my version say it should execute in here if we're in our single-threaded JavaScript environment? Um, I guess it would say, um, hello first and then me first. Right, because we've got to finish that line of code, the timeout before we hit our me first. Is that what actually happens, Matt? No. No. Huh, let's make it even odder. What if instead we delayed our print hello by 0 milliseconds?

[00:03:59]
Matt, what order would my code imply that we would? It would imply it would say hello and then me first. Is that the actual order that would happen here? No. Our regular JavaScript model that we've spent everything so far on is failing us. We're going to need to add some new pieces. JavaScript alone, this beautiful three-part system. Thread of execution, single, runs through the code line by line, memory and the call stack tracking which function we're currently running is not going to be enough.

[00:04:31]
We're going to have to add some other components. Our core JavaScript engine has 3 main parts, thread of execution, memory or posh word for a variable environment or state. The data stored in our app at that moment, and our call stack, we have to add some new components, and that is what we're going to do, we're going to need to add web browser APIs in Node, they're called background features or background APIs or Node APIs, promises.

[00:05:02]
The event loop, callback or task queue, and also the micro task queue. These pieces are not going to be in JavaScript. They are instead going to be part of an outside system. JavaScript does not run in isolation. JavaScript instead runs where? Where does JavaScript run? In the browser. In the web browser or within the Node environment, within the larger Node or computer environment. And it turns out that actually we have a whole bunch of additional features that are available to us in JavaScript from the web browser that are not actually in JavaScript.

[00:05:36]
In fact. Let's, we're going to walk through this code here, but let's start by actually just even coming up with some of the features that are not in JavaScript, and I'm going to use blue from now on for my web browser. So we have our JavaScript, I'm going to put it over here. We have our JavaScript engine with its big three things, our call stack, our thread of execution, our memory, and then we have in the web browser a whole bunch of additional features.

[00:06:11]
Can anyone give me, where it, here's your hand. Give me some of the additional features, yes, Michael. We have the DOM. The DOM. We have the DOM, that's probably the, in the top two most important. Right, that's the DOM is the bit that allows us to, is a model, the M stands for model in an object format. It's sort of big old object that describes what's on the actual webpage, so that we can interact with it.

[00:06:42]
Beautiful, from within JavaScript. Huh. What's another one, Austin? Service workers. Service workers, absolutely, Austin's favorite. Service workers. I saw Matt, yes, oh sorry, Ryan, Ryan. Console. Console! You show off, exactly. Even our console people is not in JavaScript. Well done, Ryan, that's exactly right, even our console is not in JavaScript, our dev tools aren't in JavaScript. What else is?

[00:07:09]
Yes, Michael. So we'll setTimeout and then also set interval. Oh, so you're saying even potentially timers. Are not actually a JavaScript feature. Michael's right. Why are you stealing all my best ones? Excellent. Austin, GPO. Oh, speaking to the network. So network being the internet, speaking to the network, speaking to the internet, also not in JavaScript. Can we think of some other ones? Yeah, Michael.

[00:07:34]
Fetch. Well, we're going to learn in a second, I mean that is, so fetch people will see, and we're going to use it for sure, is our ability to speak to the internet. So this is our feature ability to be the internet. Chris, it's very much a sort of interface between these, so let's leave that one out, because it's going to allow us to interact between these two worlds. So it is so embedded between the two that I wouldn't want to distinguish JavaScript versus the DOM, it acts as an interface between these two, but I guess, yes, technically, but it's such an interface between these two, let's keep that one as, we'll come to it in a bit.

[00:08:12]
What about IndexedDB? Yes, absolutely, these ones are just unambiguously IndexedDB. These are unambiguously features. Don't forget the webcam, I believe that's a, you know, a feature that we can use from the browser. I think I've, have we hit the main ones there? His local storage. Local storage, excellent. Local storage. Beautiful, not one of these people is in JavaScript, and I'm going to we're going to see, kind of, thank goodness, because all of these things can take a bunch of time, and we're going to wanna have the ability to do them without doing blocking without doing them in our single thread of JavaScript and waiting.

[00:08:57]
So we get in JavaScript, the ability to speak to any of and use any of these features directly, and that's why it is such a profoundly powerful language. I know I think closure is really cool. High order functions are nice, closure's really cool, I think closure's an amazing built-in feature of JavaScript, but you can see it's still only dealing with one thing, how do we, how do we in a sophisticated manner, think about our data and our functionality being together?

[00:09:28]
Because that's all there is, data and functionality. That's it. JavaScript would be a very unpopular language if that's all it could do. It would be a very basic language if that's all it could do. Instead, it's a profoundly powerful language because we get labels within JavaScript to use any of these features. I call them. Which is not a term that's taken off, I call them facade functions, because they're a facade, they look like they do JavaScript work, we don't see in them that they're clearly non-JavaScript, they look like they do JavaScript work when they're actually a facade for stuff outside of JavaScript entirely, that we're accessing from within JavaScript.

[00:10:15]
And let's hope, of course, people, and I'm sure JavaScript's done so. That it is chosen names for these outside of JavaScript features that map closely to their underlying feature name. I can only imagine they did, so if we want to access the DOM, we presumably use DOM, right? No, OK. What label do we use, Michael, for the DOM? Document. Document, does that seem helpful? No, I don't mind. It gets better and better, right, as new features have been released, do we notice that some of these now have the actual official name of the feature for the console, how do we access the console?

[00:10:57]
Console, that's pretty good. I know we then use the log as one of the methods available within it, but the console is accessed by console. That's pretty fab. How did we used to access the network? Anyone remember the old XHR, right, XML HTTP request? Yeah, XHR, that used to be the label we use for accessing the network. Excellent, what an intuitive name. What do we use now to access a network? Fetch.

[00:11:28]
Fetch, exactly, so even more. I mean, look, let's not judge anyone. There it is, fetch, beautiful. What about for timers? Hopefully we could say timer. No, what do we use for timers, we already heard it, I think was it Michael? SetTimeout, exactly. Or set interval or set interval. And actually we're going to see today, which is quite cool, we can actually spin up a timer using an abort signal. That will allow us to also spin up a timer and potentially maybe limit how long we run what we'll see is a fetch request, and maybe abort that based on not reaching a certain, not getting a result by a certain time.

[00:12:15]
Meaning we're going to spin up a timer through a new approach. So, probably you can already guess, we're going to need to expand our system from JavaScript, and I'm going to add down here from now on our web browser features. And we're going to have a bunch of stuff in JavaScript that does not do really all that much in JavaScript, but instead triggers work outside of JavaScript entirely, and instead triggers work within the web browser.

Learn Straight from the Experts Who Shape the Modern Web

  • 250+
    In-depth Courses
  • Industry Leading Experts
  • 24
    Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now