Higher Order Functions and Callbacks in TypeScript
This guide walks through how to work with higher order functions and callbacks in TypeScript to build asynchronous applications.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this guide, we're going to get into how to work with asynchronous behavior in typescript and we're specifically going to talk about the concept of higher-order functions and callbacks. Both of these are integral parts of how to create that asynchronous behavior that we've talked about in the very beginning of the guide.

So for this I'm going to start off by creating a method and this method is going to be considered a callback method. Now a very important thing to know about callbacks is that they are just methods there's nothing special about them. So they're callbacks in the fact that we look at them like they're a callback after we run through this code I'll walk through exactly what a callback is in detail. So I'm going to say var db query and it's going to be an anonymous function, and this function is going to return void. Inside of it, I'm going to use our set timeout again because I want to actually delay this code from running. So what I'm creating or I'm trying to mimic here is a database query. So we talked about in the introduction how asynchronous behavior is the ability to run multiple things at the same time or had to have one item run in the background and not block the other items. So here I mimicking a database query call and this query is going to be timed out for three seconds. So I'm inside of these brackets of that time out I'm going to use our fat arrow method and this is going to create a function inside of it. So for a set timeout. The process we're going to do is just a console log and say query results and then remember because this is set timeout it takes a second argument. So right here this is going to take an argument and here I'm going to say three seconds. And you say that in milliseconds so is 3000. And this is everything that we need for our market database query. So it's going to be something that runs. It's going to print out query results after three seconds.

var dbQuery = function() : void {
  setTimeout(() => {
    console.log('Query results');
  }, 3000);
}

Now create a function called load page and this is going to mimic loading a page and this function is going to take one argument and the argument is going to be a method. So this is the convention for working with callbacks and higher-order functions. So when we have a method that actually takes a method like our load page method, this is considered and it's called a higher order function. There's nothing special about it except that it simply takes a method that's the only thing there is no higher order name or anything like that. It just means that this is a method or this is a function that takes another function as its argument. So inside of this load page, we're going to use the arrow and we're also going to say that we want this to return void. So that's all we have to do in our math or in our function declaration is a load page. We want the method to return void and then inside of it we're going to have some Konsole log statements so as a console log. Let's pretend that we're importing the header and right after that we're going to import the sidebar and footer. But we want our database queries to run and the cool thing about this is we can actually slide our query right in the middle of this code. Because of javascript's nonblocking nature, this code is going to run but it's not going to hold up. The other things if you're coming from a language like Ruby or like Python if we had these kinds of consecutive code calls we would have a console log header and if we had something like this like this database query that ran for three seconds this would run for three seconds and then our sidebar would load and then our footer would load. However, because this is Javascript the way it's going to work is the header is going to load then the sidebar then the footer and then only after the database queries run will this code run.

function loadPage(q : () => void) {
  console.log("Header");
  q();
  console.log("Sidebar");
  console.log("Footer");
}

loadPage(dbQuery)

Let's test this out. A load page and remember load page takes in a function as an argument. So we're going to actually be able to paste in this database query function here and this is going to perform the query for us. I'm going to come in the terminal tsc and that worked. So now it's run node 028_higher_order_functions_callbacks and look at that everything printed out and three seconds later are query results printed out so you can kind of envision what this would look like on a Web site where the header loads then the sidebar loads in the footer and then only after everything else is there do the query results come in. If you are on a lot of Web sites on a regular basis you've probably seen this behavior all over the place where the entire site will load but the content in the center or certain components on different parts of the page won't actually load., but they don't stop the rest of the page from loading. And that's the way that typescript works and that's specifically the way javascript works with a callback kind of structure and with its nonblocking nature.

So I said this guide was going to be about higher order functions and callbacks but haven't really gotten into those I've walked through how to build asynchronous function. So now that we have all this code here and now that you see the behavior let's go through what this actually does from a component level.

Callback Method

So right here this database query this is considered a callback like you can see there's nothing special about it. It's just a function usually callback functions are anonymous methods and part of the reason for that is because you want the ability to pass them as variables just like we did right here so we can pass this database query as an argument into a load page. But besides for that as you can see there's nothing special about it. The set timeout doesn't let this part trick you into thinking that it's special at all. I just did that so we could mimic cabbing a database query if we wanted to get rid of this and run just like this.

var dbQuery = function() : void {
    console.log('Query results');
}

function loadPage(q : () => void) {
  console.log("Header");
  q();
  console.log("Sidebar");
  console.log("Footer");
}

loadPage(dbQuery)

You can see that it all works but here because it was instant query results showed up right under the header. So that's something that's very important to note that timeout did nothing to make it a callback. I don't want you to kind of get confused by that part of it. Set timeout was just there to mimic a database query behavior. And then that's really it. That's all that you need to know from a callback perspective or in order to create a callback and then from there you pass it into the higher order function.

Higher Order Functions

Now to review a higher order function is a function that takes a call back as an argument. We're going to get into later on how higher-order functions usually take a few different arguments it will take a success message and then they'll take a failure and they'll be able to work with things like you in case they say this database query ran, but it didn't return it or returned an error or something like that. You'd want your load page to be able to handle that properly. I don't want to confuse you with a ton of things that are kind of a waste of time right now because you know we'll get to those eventually and we'll specifically get to them when we start to cover promises in the next guide. Right now I just want you to focus on what a callback is. And remember a callback is just a function and it's a function that's passed inside of another function. Those functions that it are passed inside as an argument to are considered higher order functions.

If you have finished this guide and you know those two terms and what they do at a high level and you've been able to see the behavior of what it looks like when you run through these then you are in great shape and you are in really good position to work with asynchronous behavior in typescript.

Resources