If you’ve ever had the pleasure of enjoying a drink with a .Net developer and stumbled into any form of a C# VS insert language here, then you’ve probably heard about they dynamic duo of the async and await keywords. Sadly, our .Net loving friends are right that they are really on to something, but it can be a little hard to understand what exactly they’re talking about, especially for those of who come from development traditions that don’t have the concept. Simply put Async / Await solves a huge problem that effects basically every non-trivial piece of software ever written — asynchronous programming. In simple terms asynchronous programming is basically any code that deals with the fact that some things just aren’t instant and modifies code flow (in other words the order that individual lines of codes are executed) to guarantee that things happen in the correct order. That’s a mouthful but let’s look at a sample of some pretty linear code to illustrate the point. As always, we’ll be using a our favorite dueling monsters to make our point.

charmander.attack();



// Inside Our Charmander Class



public void attack() {

channelFireGods();

shootFire();

}



That looks pretty straightforward if not a little silly. But wait… surely channeling the fire gods can’t be instant can it and it appears to be another method on our imaginary Charmander class, so that seems like a problem. In fact, it is. As written now this code would do one of two things: either block your user interface thread and freeze up your whole application or shootFire() would execute before channelFireGods() finished, horribly embarrassing our Charmander and Pokemon trainer.

Taking a look at our first failure case here of completely locking up your user interface thread and therefore freezing up your entire application, it’s pretty obvious what our problem is. Whatever is actually done in channelFireGods() is simply slow and because our program as written currently is synchronous that means (at least on most platforms) code execution is completely halted; God forbid you’re developing an iOS app and something like this happens, you’ll be drowning in one-star reviews.

An obvious solution to this app would be to simply run that pesky channelFireGods() method run on a background thread rather than the main thread. Threading is a huge topic and fairly complex computer science problem and well beyond the scope of this post, but on an basic level is running code in different silos (the aforementioned threads), so that long-running code doesn’t block the flow of code execution; again, I am aware that is a dramatic over-simplification. Manually managing threads is as error-prone and complicated as it sounds, so a lot of languages and frameworks offer simple executeInBackground() methods. Of course, nothing is easy and while those solutions prevent the blocking issue, they also make your code run in a not linear way; in other words we encounter the issue from our original example above where our fire-breathing pal doesn’t finish his channelTheFireGods() method before shootFire() is executed. Languages have all sort of ways to handle this problem. For example, C-based languages like Objective-C have blocks and Ecmascript has callbacks such as. Here’s an idea of what our little fire-breather might look like in some psuedo-Ecmascript:

class Charmander {

channelFireGods(successCallback, errorCallback) {

// let's assume there's some long-running operation to call the gods

// let's also assume we are old-school and got a success result and go on

let success = someResponse.result;

if (success) {

successCallback();

} else {

errorCallback();

}

}



shootFire() {

channelFireGods(function() {

// Now that we are ready to fire, actually fire!

}, function() {

console.log("an error occurred -- failed to fire");

})

}

}

Even in this extremely simplified example, we see that things can get a little rough with callbacks and it’s completely possible in a more realistic or complex scenario that the methods we use in callbacks might themselves have callbacks; that’s what programmers often refer to as callback Hell. This works but isn’t very clean and eventually with enough nested callbacks becomes very difficult to maintain. That’s where the wizards of Redmond come in and give us a more elegant solution.

Assuming we have Async / Await, let’s take a look at what our Charmander class’ shootFire method would like:

charmander.attack();



// Inside Our Charmander Class



public void attack() {

await channelFireGods();

shootFire();

}





There are of course some details left out of this. In particular the slight modification that would need to be made to channelFireGods() to return a Task as required; if you’re interested in learning more about the specifics of Async / Await in .Net, take a look at this MSDN post. The practical result of what’s happening here is that the execution of the attack() is paused until channelFireGods() fully completes and once it does it continues on to execute the next line as normal. Basically, we are making sure our little fiery friend has communed with his fire gods and is ready to scorch even the most arrogant of Pikachus. Cool right? What’s really happening behind the scenes is pretty clever. The code flow is being managed in a way to make sure that channelFireGods() completest before moving on without you as the developer having to add any complexity to your top level code; in other words, the compiler is basically modifying your code one level down to handle the complexity without making you bother with it.

This Async / Await pattern has been so successful and frankly useful in .Net that many other languages and platforms are adopting it; Ecmascript has already brought it in and there’s already a primitive version of it for good old C++. What do you think? Are you looking forward to using this pattern in your code or is it a little too magical for your tastes? Let me know on Twitter and take a look at my company The Mad Botter if you have any custom software needs.