Check out a free preview of the full Rethinking Asynchronous JavaScript course

The "Exercise 2" Lesson is part of the full, Rethinking Asynchronous JavaScript course featured in this preview video. Here's what you'd learn in this lesson:

In this exercise, you will write the same async flow-control code using thunks instead of callbacks.

Preview
Close

Transcript from the "Exercise 2" Lesson

[00:00:04]
>> Kyle: Exercise two calls for you to do the exact same thing as we did in exercise one, except now we're gonna use thunks, okay? So if you open up the Read Me in the EX2, we have the exact same set up. Should look the same to you. No complexities different.

[00:00:24]
But it is this line right here, line 23 in my code. That's the one I want to call your attention to. The getFile function is your thunk constructor. GetFile needs to produce a thunk. The question is, should your thunk be lazy, or should your thunk be active? If your thunk is lazy, are we going to be asking for files in parallel the way we want to or not?

[00:00:52]
If your thunk is active, will be asking for them in parallel? Okay, so first task, figure out how to make the thunk. And second task, which you may actually want to do these in reverse order, is figure out how am I going to use those things to sequence their outputs?

[00:01:14]
So I'll give you five. Let's call it eight minutes to play around with the stunt. Remember we're not using any libraries here, we're just simply using the notions of function in closure in a different way. You're not gonna need any global variables here. So if you go down the route you did in exercise one, you're doing it too hard.

[00:01:31]
We'll see what you come up with.
>> Speaker 2: Quick question. They're asking if you go over slide 40.
>> Kyle: I did go over slide 40.
>> Speaker 2: Again, but did you review it?
>> Kyle: Yes I did review.
>> Speaker 2: Okay sorry.
>> Kyle: I can review it one more time. The function created in line seven is hard coded to know that the addAsync function is what it's going to call.

[00:01:56]
And it also knows two of the three things that it's gonna pass in. It knows that it's going to pass in a ten and a 15, but it doesn't know what callback it's going to pass in. So it's hard coded to know addAsync and ten and 15, and it's waiting for callback to be parameterized.

[00:02:13]
We parameterize that call back on line 11. We passed in a call back to that thunk. That is what invokes the addAsync function with ten, 15, and the callback we passed in. Line two sets up a timeout, and after a thousand milliseconds it calls the callback passed in.

[00:02:31]
Passing in the values that are at the addition of ten and 15, which is the value 25. Which then comes back to line 11, the parameter sum has the value of 25.

Learn Straight from the Experts Who Shape the Modern Web

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