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.


Transcript from the "Exercise 2" Lesson

>> 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.

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?

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?

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.

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.

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.

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.

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