JavaScript: The Hard Parts, v3

setTimeout & fetch Execution

Will Sentance
Codesmith
JavaScript: The Hard Parts, v3

Lesson Description

The "setTimeout & fetch Execution" 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 walks through a code example that includes setTimeout and fetch. When fetch is called, it triggers a network request and creates a promise object that holds the future result. The promise stores functions to run once the data arrives, using the .then method to add these functions to a queue. This setup allows JavaScript to continue running other code while waiting for the network response, then automatically execute the stored functions with the retrieved data when ready.

Preview

Transcript from the "setTimeout & fetch Execution" Lesson

[00:00:00]
>> Will Sentance: Well, we have just seen the remarkable fetch, five letters that changed the world of JavaScript. Two prongs: one was hitting our web browser features and the other was hitting our JavaScript with a placeholder object into which the background work would eventually load its data. And we then attached to it a function that would then run automatically when that data was retrieved, in this case from TikTok.

[00:00:31]
So now, let's see when that work is complete, what the heck are the rules for that data getting back into JavaScript. We just said when the background work completed, let's have our display function from the promise object added to the call stack, but we know it can't just go on the call stack. We know that we have to have some sort of queue or rule for getting that data, getting that function back on the call stack.

[00:00:58]
So let's see it all in full here, in what is going to be a wild ride of diagramming. We've added three functions here. We're going to have both the old school style setTimeout with the callback, no two prongs there, and the new school with the fetch, two-pronged consequences, both promise and web browser work. You know, you have to tee yourself up for something. Here we go. We have our JavaScript, we have our memory in our global execution context in our JavaScript engine.

[00:01:42]
We have our web browser features. Is this enough room? Maybe that's enough room. We have our web browser features. Oh dear. Okay, we have, maybe I'll just do it without the, we have our web browser features, yay, web browser features or APIs. Beautiful. And we have our call stack that keeps track of what code is running and where we are at in our thread of execution in JavaScript. So let's get into, I mean, we have all our system here, right?

[00:02:24]
Thread of execution, memory, call stack—that's JavaScript land. Maybe even draw a little box around it. That's JavaScript land. We have our web browser land below. You know what, let's put our callback queue in now. We know that's definitely part of our system. Callback queue is now a part of our system. Let's put in our event loop because we know that is also now part of our system. We'll do our little thing.

[00:02:54]
It's checking: anything in the callback queue? Is the call stack empty? Is global code running? We can move stuff from the callback queue to execute it on the call stack. That's not a bad baseline system to be working with. And then I guess we could say we have over here, off at TikTok's headquarters, we have our server, a computer connected to the internet, ready to receive requests from our computer system, our computer, our web browser.

[00:03:31]
Okay, everyone happy? Oh, we have a console. There's a lot of stuff that computers do. Very powerful. Okay, I think we now have a full template. You could even copy this out on your notepad and see how the system runs for any situation. I could even release a series of notepads that you could buy with pre-drawn. That would be fun. What a fun gift that would be for all your friends, neighbors, and loved ones and your worst enemies.

[00:04:05]
Okay, here we go. Let's go. We've got three functions to declare. Let's start with Michael. Declare me my three functions here. Okay, we first declare a function called display. Do you want me to say the... No, no, because in the end we just grab all of its code, stick it in memory. We don't, I don't even like to talk about the body of the function until we call it because it gives the impression we're evaluating it in some way.

[00:04:27]
We don't touch it until we call it, so then we need to say what function next? Alright, so we declare a function called printHello. Beautiful. And then we declare a function called blockFor300ms. Right. And we're not going to see how that one works because it would take too much space, but we know it's going to do some sort of long loop, lots of different small steps that will take 300 milliseconds and block the single thread of JavaScript directly, not set up some background work, but do it directly in JavaScript when we call it.

[00:05:00]
Okay, now we go straight into some actual code execution. What's our first, talk me through that next line, Michael. Alright, so we call setTimeout with our function printHello passed and a value of zero for the time. Perfect. So we are, are we doing anything of interest with this function here in JavaScript, Michael? No, we don't, we can't see the execution of it, so we don't go into... No, that's right, exactly.

[00:05:32]
We are heading off with this function off to our web browser where we are going to set up what background feature, Michael? What a setTimeout trigger in the web browser? The creation of a what? A timer. Excellent, Michael, absolutely. Do not fear, Michael. Believe me, that is an experience as old as time. And what does a timer need to know here? What information does it need to have, Michael? The function it's going to call at the end.

[00:06:13]
Yes, nice. And then the time it's going to wait. Yes, in milliseconds, exactly. So zero means it's going to wait zero milliseconds, and when it is complete, on completion, it is going to call what function again, Michael? PrintHello. PrintHello, spot on. PrintHello is going to be called back in JavaScript, so actually it just passes a link back to the printHello function, a reference back to the JavaScript printHello function in memory.

[00:06:47]
Almost there. So then, is it complete? That's my question. Is it complete? And the answer is, at zero milliseconds, is a zero millisecond timer complete? Sounds like a trick question, but it isn't. Is it complete, Michael? Yes, it is. Spot on. So our printHello function is going to be out of the call stack. No, no, where's it going to go? Going to the callback... Callback queue, in it goes. PrintHello, there it is.

[00:07:20]
Oh, I think it's going to be, so it gets in there at zero milliseconds. I'm sure it'll be allowed back on the call stack before long. Who knows? Alright, happy. I can, I'm just like, you can imagine people who just like, I hope I can track all the stuff that's happening. I'm happy. So we've now finished with this line's work in JavaScript in completion, and so we hit our next line of JavaScript at about one millisecond, but really it's faster.

[00:07:56]
But just in order, we're going to hit the most pain in the ass complex five letters, powerful five letters in JavaScript. Let's go to Joe. Left-hand side, what am I declaring? A function definition or, sorry, a const of a variable futureData. Perfect. And on the right-hand side, what am I calling? Fetch. Absolutely, which I'm with a passing a parameter of an argument, string. Yeah, yeah, yeah, an argument with a string that contains a domain and a route.

[00:08:31]
Perfect. This fetch, people, does it do two main things? Two main, exactly. It has a consequence in the web browser. Let's start with that one. It's going to kick off work by which web browser feature? It's going to use fetch. Well, ooh, I wouldn't even say it's going to use a network request feature. I could probably, yeah, exactly. Yes, it's going to use the network to do a request. And what information do we get for that request?

[00:09:07]
Yeah, we have the domain and the route. Yep. And we will implicitly be sending a GET. Yeah, I like that, exactly. It's going to automatically be a GET request. There's our route, our path, and it's going to automatically say go get some data, which at one millisecond it does. Off it goes to TikTok, and it sends an HTTP message saying, excuse me, I need to get some data. And it sends that at roughly one millisecond, and it wants to get whatever the cute puppy video is that I've uploaded to my TikTok at that path, at the /will.

[00:09:48]
Okay, it's also... Yeah, yeah. Give me one second. You're right, you're right, but first, no, you're so right, Joe, but because it's got so much going on, let's also just check at one millisecond, is this work complete? No. Absolutely not. Lots of work to do there. But as you, and on completion, well, as you say, we're going to need to get our other consequence from fetch, which is what? We're spinning up a promise object.

[00:10:23]
Yes, exactly. We're creating a promise object that is going to be stored into futureData that is holding results. Exactly. It's got some hidden properties on it: value, undefined for now, and then this onFulfilled array. Exactly, fulfill reactions, but we'll just put onFulfilled for now, which is going to be an empty array into which we can store all and any functions that we want to have run when value gets automatically updated because on completion, our network request in the web browser is going to have a reference to that object that was created at the same time from the two-pronged fetch that is now stored in futureData.

[00:11:16]
Our immediate output from the call of fetch has to be a live thing. It can't be a go do some work on the internet, and that live thing is this special promise object with its hidden properties, which we can see in the console, but value, which is undefined, and the onFulfilled array, which we as yet have nothing in. On completion of that background work, what is going to be updated back in JavaScript memory, Joe?

[00:11:53]
Well, we'll get the data, so the value. Exactly. FutureData.value. Exactly. We'll be set to whatever data we get back from speaking to TikTok. Excellent. Let's give Joe a hand, very good from Joe, deserving of a hand. People, everything we've done here has all been a result of these five letters. Have I missed anything on what fetch does there? Actually, I'm asking somewhat literally and somewhat rhetorically.

[00:12:21]
Hopefully I haven't. But we do know we want to have some code run on the completion of that background network request and on the update of our value, because, yeah, I sort of missed this. We know that as soon as this value property is filled with actual data, any functions in here will automatically be called, and their input will be that data. So we need to add some functions there, and we can't push into a hidden property, a hidden property with an array on it.

[00:12:51]
We can't push into that directly, so we get a built-in method available on futureData. Joe, what is that method? So we're on the next line in global now, right? Yeah, in which we're calling .then. Exactly. And that gives us access to this array, and we're passing what function to that array? Display. The display function, which we hope we've defined with a placeholder in it, ready to receive the data that will automatically be inserted in it when it gets executed automatically by JavaScript later on.

[00:13:20]
Let's hope. Did we? But we're not running it now. We're not running it now, but we did include a parameter data ready to be filled in and used. So this grabs our display function, which, as you say, key point from Joe there, we are not running that display function now. I don't even love the term then. Then should be called instead something like addThisFunctionToRunLater, because I think that then in a sense implies we're doing it right there and then.

[00:13:51]
I mean, or you could say it doesn't, I don't know, but to me, what we're doing there, or what we're literally doing, is grabbing that display function and saying on futureData, when the data returns, you can then run that function. So essentially add our display function to this onFulfilled array, and that is where display will now be stored, so we can sort of show that as, I guess we can show it here, right?

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