The HTML5 Diaries – 6 – The Tough Bits

This is the last part of the HTML5 Diaries, covering the Microsoft 70-480 exam. So far, we’ve looked at the basics of HTML5, including semantic markup, Canvas and the new form API. We’ve also looked at CSS3, and how we can use CSS to change how our markup is presented. We’ve also looked at Javascript, in all its weird and wonderful glory.

In this blog post, we’re going back to Javascript and we’re going to look at some really, really advanced topics; Web sockets, web workers, exception handling and promises. The contents of this tutorial corresponds with the final video on the Microsoft Virtual Academy.

The way this lesson is going to be structured is going to be a little bit different from previous lessons. I’m going to explain the theory behind each of these topics, but there isn’t going to be a great deal of code behind them. Rather, I’m going to point you in the direction of some other blog posts and tutorials.

Make no mistake, these are huge, huge topics. I couldn’t give them justice in just one blog post. That said, I’m going to try and introduce them in a really gentle manner. Now, if you’re just coming here, you probably want to start from the beginning of the series. If you legitimately have no idea what the hell I’m on about, you might want to read up about the Microsoft HTML5 exam. Click here for more information.

So, let’s begin.

Exception handling: What is it, and why should you care?

So, suppose you’re designing a highway. You expect your highway to link two major cities and to carry lots of traffic. What happens if a truck overturns on your highway, causing a major pile-up and severing all lanes?

Well, the first thing you’ll want to do is to let people know that there’s been a pile up. You’ll also want to funnel traffic through alternative routes so that you don’t end up with a massive backlog of cars. Exception handling is basically the procedure that you do when a lorry overturns on your highway. The highway in this analogy being your application.  Douglas Crockford defines exceptions as this:

“Exceptions are unusual (but not completely unexpected) mishaps that interfere with the normal flow of your program.”

When you set up exception handling, you’re basically defining a set of behaviors that the program will enact whenever things go south. So, let’s look at the example the good Mr Crockford gives in Javascript: The Good Parts.

var add = function (a, b) {
if (typeof a !== ‘number’ || typeof b !== ‘number){
throw { name: ‘TypeError’, message: ‘add needs numbers’ };
} return a + b;
}

So, what are we doing here? We’re defining a function called ‘add’ which takes in two inputs. Inside the function, there’s an if statement which checks if ‘a’ and ‘b’ are both numbers. If they aren’t, the Throw statement is called and that interrupts the execution of the function. According to Javascript: The Good Parts, a throw statement should be given an exception object which contains a name property and a descriptive message property. Name property just identifies what’s gone wrong. The message adds an element of description.

When you use that function, you’re going to want to catch the exception that is thrown. So, let’s use the ‘add’ function we defined earlier incorrectly and see how we meaningfully use exception handling.

try {
add(“cactus”);
} catch (e) {
document.writeln(e.name + ” : ” + e.message); }
}
So, what have we done here? We’ve called the ‘add’ function from within a Try block. Now, if we successfully use the add function, happy days. The program will continue its normal flow and continue to the next bit of the program. If you recall, the ‘add’ function is expecting two numbers. We’ve given it a string of characters. That’s unexpected behavior, and will cause the function to throw an error.

That’s where Catch comes in. Catch basically catches the exception that is thrown and assigns it to a variable called ‘e’. Within the Catch blocks, it will then print out the name of the exception along with the descriptive message. And that’s basically that. From here, I suggest you check out chapter five of Eloquent Javascript. Now, let’s look at some harder stuff.

Promises: I promise the next few paragraphs will not use long winded analogies.

I lied.

Imagine you’re working as a software developer for a big company. You’re a busy guy, and lunch comes and you’re really, really hungry. So, you go down to your favorite Mexican place to get some tacos with your laptop so that you can do some work.

You go into the restaurant, find a space, put your coat and bag on a chair and stand in line to order your food. When it’s your turn, you order the beef tacos with some nachos and you return to your table, as you await your food.

Now, you’ve paid for your lunch, and the people in the kitchen start cooking it. You know the food is going to come. You’ve given the teller money for it, after all. Do you take your laptop out and start working?

If this is the real world, the answer is yes. But with Javascript, it’s a bit more complicated.

Suppose you have a function that does a lot of stuff, and therefore takes a while to execute. About 100ms. Now, Javascript normally would wait and block until that function is fulfilled. Now, suppose that you’ve got other stuff in your application that uses Javascript? UI elements, and all that jazz.

Well, they’re not going to do anything until that function you called finishes what it’s doing.

Promises work by returning a dummy value, allowing your application to do other stuff. Once the function has finished its task, it’ll return its true value.

Promises are really complex, and other people have explained them better than I could have in just these few paragraphs. Have a butchers at this blog post from Bryan Klimt (of Parse.com) and this one from the MSDN.

Web Workers: (Web) Workers Of The World, Unite.

So, what are Web Workers? Consider this (admittedly terrible) analogy.

Professor Gerhard has a brilliant mind. He’s at the forefront of evil science. His advancements in apocalypse summoning technologies are world renowned. His advancements in the fields of mind control and hypnosis have won him many Evil Nobel Prizes. Unfortunately, Professor Gerhard has limitations.

Despite being an evil super-genius with an army of minions and a death ray, he still only has two hands and one brain. He can only do one thing at a time. He’s just a person, after all (albeit, an evil one). So, naturally in a quest to augment his productivity and to speed up his quest for world domination, he decides to clone himself.

He attaches a phone booth to the top of his towering fortress of solitude and waits for a lightening storm, like an evil Marty McFly. Eventually, a bolt of pure energy strikes the red phone booth in which he concealed himself, and blue bolts of energy surges through his veins, knocking him over. He hits his head of the floor, speedily rendering him unconscious.

Eventually, he comes to. His blurry eyes focus. And who does he see? Himself, standing over him. It’s his clone, spawned from the high voltage that was pushed through the red iron chassis. Now, with his clone, he is unstoppable. The 80’s rock band Power Tool once said that two heads are better than one. They were right.

So, where does this terrible, terrible analogy fit to Javascript? So, Javascript is like Professor Gerhard. Despite being this powerful, object oriented, Turing complete language, it can only do one thing at one time. It’s not concurrent.

These things called Web Workers are the only way to do concurrency in Javascript. The Javascript language itself is single threaded. The way it works might be seen a bit hack-y, but it works nonetheless. You’ll define the behavior that you want to execute in a bunch of external scripts. You then call them when you need to by spawning a new worker.

Communicating with these scripts, or web workers, is done by using something called Messaging. It’s also worth noting that web workers can’t mess with the DOM, so if you want to use them for cool hacks with your markup, think again. HTML5 Rocks has a great article about Web Workers. I’m just going to leave it with you, and let you carry on from here. It’s a big topic, after all.

Web Sockets – More Fun Than Deleting System 32

Web Sockets are interesting. Think of them like R2D2 in Star Wars: A New Hope. There he was, just a normal R2 droid, loitering about on Tattoine, spending his dusty days getting shot at by Jawas and sold to the ill-fated Lars family. And then Bam. He’s shoved into an X-Wing with Luke Skywalker and the rest of Red Squadron, shoving a torpedo down the cakehole of the Death Star. In short, they add this extra abstraction of awesomeness to Javascript and to your HTML5 web application. They add lasers to your application.

So, enough with the astonishingly tenuous metaphors. What do Web Sockets actually do? They basically allow your web application to have its own network connectivity. Pretty cool, right? With them, you can create a continuous, persistent connection to a remote server, and send and receive data to and from said remote server.

Where would we use Web Sockets? Think things where high latency is bad. So, you’re talking about your browser based multiplayer video games (especially first-person shooters) or web applications where data needs to be readily and frequently updated and is time sensitive, like stock tickers. A cool thing about Web Sockets is that you can send data either in the clear, or encrypted. Web Socket functionality is also present on most web browsers. Even Internet Explorer has Web Socket functionality!

Web sockets are kinda hard to comprehend at first. As I said at the start of this blog post, I’m not going to scare you off with heaps of code. I’m going to point you in the direction of some amazing resources. And most fortuitously, HTML5 Rocks has a great lesson on them. Check it out. If you’re feeling brave, have a look at the RFC for the Web Sockets protocol.

RFC stands for “Request For Comments”, and they’re used by computer scientists to debate and design standards for protocols. By reading the RFC for web sockets, you’ll find yourself getting a really deep level of understanding for what Web Sockets actually do.

Fin

This concludes my six part tutorial on the Microsoft HTML5 70-480 exam. I wish you all the best success with your exams. If you have any comments or questions, please leave a comment below, or ping me an email here.

About Matthew Hughes

Matthew Hughes is a software developer, student and freelance writer from Liverpool, England. He is seldom found without a cup of strong black coffee in his hand and absolutely adores his Macbook Pro and his camera. You should follow him at @matthewhughes.

1 comment

  1. More then anything else in JavaScript, lean how to use Promises – A good number of “OMG why is this happening?!?” problems people face with JS can be solved by using them correctly, and using them even badly can in some cases be a benefit and better then noting at all when you hit async madness.

Leave a Reply