The Great Escape from Callback Hell

Making no Promises. Using generators and finally understanding async/await in-depth are all covered in this edition of my Medium JavaScript tutorial article — JavaScript Teacher @js_tut on Twitter.

You can find my react.js book on Amazon here. Support is appreciated. -jst

It’s about time you know async and await. You know you wanted to for a long time. But for some reason… you just never got to it.

Only knowing about the keywords: yield, then, async, and await is knowing nothing at all. You want to gain thorough understanding once and for all.

At this evolutionary stage of JavaScript you simply must understand it today. And this article will walk you through the whole enchilada.

First things first.

These are the basics of JavaScript events. In ES6 we also have arrow functions.

Okay. That’s the easy part. Moving forward.

So you’re at a point where you want to make a bunch of HTTP requests. And you decide to tie them all up together into a nice little hierarchy. But there is one more thing you are forgetting…

3. Chained events can quickly turn into an experience of Callback Hell.

This is especially true of events that retrieve JSON from codependent API endpoints via HTTP requests. Specifically, when next callback is blocked by data it must first retrieve from previous endpoint:

The proverbial JavaScript Callback Hell and none other.

4. Promise me it won’t ever happen again.

To battle the problem of syntactical mayhem some wise man created the idea of a Promise. What are the basic principles behind them?

1. Promises provide control over result of a callback: to resolve or to reject.
2. All Promise objects have .then() method attached to them.

5. Promises produce cleaner code.

You cannot sail the ocean until you build the boat.
Let’s make some Promises:

Treat unusual vertical bars surrounding strings as “ quote characters. I decided to leave them out here in this screenshot because it looked unusual. But also more interesting. You get bored with JavaScript staring at it at work for hours on end at work. Sometimes I wish double quotes looked just like this.

Return value: each Promise returns another Promise, making chaining then statements convenient. In some cases you can even remove arrow function and make the code look even more compact. JavaScript can now treat a function as a return value.

6. Best practice for Promises? (Other than keeping them IRL.)

There are two unique cases when using Promises depends on whether it matters which order events are executed in. Both examples below are considered best practice for each individual case:

7. We can end up in Promise Hell too when Promises are used incorrectly

Not all that shines is gold. Problems arise when Promises are not used as intended. When wrongfully used you can witness the same problem callbacks created earlier:

You can get stuck in Promise Hell while trying to resolve codependent promises in an ordered sequence.

So how do we get out?

8. Generator ‒ The Iterable Function.

A generator is not a Promise. It is only a control flow construct. They just work with Promises. Generators execute asynchronous events without blocking your code. But make the code look like regular synchronous code!

Generators in JavaScript are defined using a <function with a star> syntax.

Along came Bluebird. A Blue Jay? Jay Query? Put that drink down.

In Bluebird, all of what you’ve seen above is already packed into a convenient method coroutine on Promise object. So yes you can tinker with your own generators in great detail. Sort of like car mechanic with his engine modifications. Or you can use Bluebird to start working with generators quickly without worry. Most developers make that choice:

And that’s pretty much all to async. But wait, didn’t you mention async and await as actual keywords in JavaScript? Glad you asked.

Yes, indeed. In fact, when you heard of async for the first time, you heard of it as a JavaScript keyword. But wait, what did we just do all this time?

Well you see, generator’s yield is the building block of async. That’s why I waited so long until I got to this point.

I won’t go into details on their differences and similarities here right now. I plan to talk about this in my next article. But…I will just show you the async keyword in action. It’s very similar. Except the syntax is a little different:

Finally this is what async | await construct looks like in JavaScript.

Congratulations.

You now have a handful of techniques to keep you away from Callback Hell.

You can follow me on GitHub – I follow back!

This article was sponsored by Learning Curve software literature publisher.

React.js Book: Learning React JavaScript Library From Scratch. Mrrrow.

For future reading check out React.js Book: From Scratch. (You have to be pretty new to React as the book assumes no previous XP whatsoever.)

Interested?

Click here for Amazon reviews

Thanks for reading!

JavaScript Teacher

I am @js_tut on Twitter.