Developer Tea

Async Code & Promises

Episode Summary

Today we talk about JavaScript's asynchronous abilities. Today's episode is sponsored by WooCommerce. WooCommerce is customizable eCommerce built on WordPress. Powering over a third of all online e-commerce stores, with WooCommerce you own all of your data, forever. Use the code "developertea" for 25% off on WooCommerce.com. Head to https://spec.fm/woocommerce for more info.

Episode Notes

Today we talk about JavaScript's asynchronous abilities.

Today's episode is sponsored by WooCommerce. WooCommerce is customizable eCommerce built on WordPress. Powering over a third of all online e-commerce stores, with WooCommerce you own all of your data, forever. Use the code "developertea" for 25% off on WooCommerce.com. Head to https://spec.fm/woocommerce for more info.

Episode Transcription

Hey, everyone, I'm welcome to you, Developer Tea. My name is Jonathan Cutrell, in today's episode, we're talking a little bit about asynchronous JavaScript and promises. If you've written much JavaScript, especially if you've written JavaScript for the browser or JavaScript that interacts with an API, those are two pretty specific examples of when you're going to encounter this, but really all over the language, you're going to encounter the need for callback functions. This is where we're going to start the discussion on promises and on asynchronous JavaScript. JavaScript is fundamentally prepared to deal with asynchronous behavior. The reason for this is because JavaScript has something called the event loop. Basically, the job of the event loop is to take different tasks, different operations or calls, function calls or declarations and take them from a queue. It takes them from a queue, a lineup of these declarations or function calls and puts them into the main call stack. The call stack is effectively the JavaScript running. When you first run your file, your JavaScript file, all of your synchronous code is going to run and then return and be removed from the call stack. Consider this kind of your currently in progress. That's what the call stack is. You have a currently in progress and it can only hold one item at a time. JavaScript allows you to do certain things synchronously, for example, setting a variable. Basically everything that you write in your JavaScript application at the top level, so whether that's a function call or setting a variable or creating an object, whatever those things are, those are all considered synchronous calls. Even if you do something that sets an asynchronous call into motion. What happens is, let's say, for example, you run set timeouts. Of course, there's plenty of resources on the internet that can tell you a little bit more about what set timeout does, but set timeout actually sends that call outside of your main processing stack. That main processing thread sees that you want to call the web API for set timeout. That runs over on the browser. This is something that is not internal to JavaScript. It's external to your single thread. Once you call set timeouts, you're basically sending that out to the web API. When the web API is done with the timing aspect, so you say set timeout and then you pass 5,000 milliseconds. After 5,000 milliseconds, the web API has gone through that time and then it sends back a message to the queue. This is the queue that the event loop has access to. The way this works is the event loop will take that item off of the queue and put it on the call stack once the call stack is empty. That's a lot to take in and a lot of this is actually covered in a great talk by Philip Roberts. Philip did this talk at JSConf.eu back in 2014 and it's called what the heck is the event loop anyway. I highly recommend you check it out. He goes into a little bit more detail, has more examples. This is how asynchronous code works. You send out some kind of single call to a separate API, whether that's the web browser API or for server side JavaScript, it's a C++ API and all of that stuff is hidden away from you. You don't have to worry about managing the return of that call until it comes back. The way that you manage it when it comes back, the event loop will grab that notification. Effectively, what it is, that notification or that call from the queue that has access to and put it back onto the call stack. What does this mean for you as a developer? That's a lot of technical discussion, but what does it mean for you as a developer? For young developers, what this often means is that things that you expect to happen, for example, if you're setting a variable equal to an Ajax call, you may expect that variable to be equal to the data that you're trying to grab from an external resource. You're saying something along the lines of let data or var data equals, and then you're running your Ajax request. In jQuery, it's dollar sign.ajax, you pass your URL. When you try to use that data, while it's letting you know that actually that variable that you set is equal to an instance of a promise. Hopefully, you've done enough googling to know that really what you needed to do was have a way of responding to that asynchronous callback, that the web API is sending to your event queue, and that your event loop is picking up and actually executing on the call stack. That's how a lot of your, especially the early days of your coding, you will probably write a lot of inline anonymous callback functions. That's what they're called. Whether or not you know that doesn't really matter, but anonymous callback functions. That just means that you're writing something like set time out, and then you're passing in the function, you're adding a comma, and then you're adding the amount of time that you want to set that time out to last for. Now, as your applications grow in complexity, and as your applications depend on many different actions happening in many different places, you're going to realize that callbacks end up being a little bit difficult to handle. Even two or three callbacks deep, and you start to get to some pretty unwieldy code. Not only that, but you're also typically depending on multiple callbacks to run in sequence. In other words, you're only running your second asynchronous call. Let's say you have two or three API calls, and you need all three of them to actually perform some action. If you're nesting each of those calls inside of the callback, in other words, if you're running some kind of asynchronous function, and then you're waiting for that asynchronous function to come back, and then you run the next asynchronous function, and then you're waiting for that asynchronous function to come back, you're probably going to run into some performance issues. It's going to take too long for all of those asynchronous functions to run. And in effect, if you think about it, this takes a little bit more thinking, but in effect, you are running those asynchronous functions synchronously. If you're waiting for one to finish before the next one finishes, then you're not actually taking advantage of the asynchronous nature of JavaScript. And the asynchronous nature of JavaScript is one of its most powerful features. And you understand it. So how can we manage our JavaScript callbacks, especially as it is related to asynchronous functions? How can we manage our callbacks in a more effective manner? We're going to talk about it in just a few minutes. Right after this quick sponsor break, I'll give you a hint. The answer is going to do with promises. Today's episode and every episode this week has been sponsored by WooCommerce. WooCommerce is customizable e-commerce built on WordPress. They were launched in 2011 and acquired by Automatic last year, going Google automatic, by the way. That's a-u-t-o-m-a-t-t-i-c. If you're interested, WooCommerce is by far the most popular online e-commerce platform. It powers over 37% of all online stores. It's built on WordPress. It's open source and it's fully customizable. Of course, since it's open source, you get to keep all of your own data. There are no limits and it integrates with popular e-commerce service providers like PayPal, Stripe, the Postal Service, and Royal Mail as well as hundreds of local services. WooCommerce powers some really cool sites. You can go and check out, for example, Moment Lens. If you're into iPhone photography, you may enjoy Moment Lens. This MomentLens.io. That's an example of a store that was built on WooCommerce. WooCommerce is offering you as a developer 25% off on WooCommerce.com. Just go to spec.fm slash WooCommerce. That'll take you straight to the page. Make sure you use the code Developer Tea. That's Developer Tea. That's 25% off that WooCommerce is offering. Then you can begin to WooCommerce for sponsoring today's episode. We're talking about how to handle asynchronous code in JavaScript. Basically what we're talking about is how to handle control flow in your application. Let's say, for example, that you want two or three things to be true before you run a particular function. You can create a promise. The promise is a particular kind of object. JavaScript actually has promises natively now, but there are other libraries that actually just extend the value that the native implementation of promises allows and also allows you to use them in browsers that have not yet implemented promises, but promises allow you to execute code when that promise is resolved. Let's say, for example, that you have two or three asynchronous calls to external libraries, to external APIs. A promise would allow you to wrap all two or three of those calls and run a callback function when all three have successfully completed. The native implementation also allows you to run what's called a race between multiple internal conditionals. They call them iterables in the documentation. You'll need to read a little bit more on the documentation. Of course, we can't get any deeper in terms of explaining the code without telling you word by word or character by character what the code is, but effectively, a promise allows you to wrap one or more other actions and then respond to those actions one or more times. Of course, you can respond to the failure state as well. On top of this, promises allow you to chain promises. If you have a promise that returns another promise or if you have a promise that returns more data, you can then chain another.then statement to the end of the original promise. As a general rule, there are two branches that a promise can follow down. It can either be fulfilled or it can be rejected. There are multiple ways that you can go about. You can manually call, for example, you manually call the fulfill side of the promise. By the way, promises have the extra added benefit that you do not necessarily have to have asynchronous code to use a promise. I'm going to leave that up for you to figure out how to apply. In a perfect time for you to apply some of this newfound knowledge, hopefully you'll go and read some more documentation beyond listening to this podcast. A perfect time for you to apply it is in the Developer Tea JavaScript January contest. Remember this contest runs until about February 5th. There's going to be at least six winners. All six will receive a year, a Copenh Pro for free, to enter you create a pen on code pen. The rules are very simple. The pen needs to rely relatively heavily on JavaScript. This means more than just a few lines for switching a class or something like that. Use JavaScript as kind of the primary feature in your pen. If your pen gets the most hearts and the top six will be the winners. If your pen receives the most hearts on code pen, then you will be one of those six winners. You can create more than one pen as long as you tag it correctly. The tags that we're going to be using are JS January. By the way, I incorrectly said that you would have to make it all in word. You can still make it all in word, but you can also use spaces in your tags on code pen. JS, space, January, JS, no space, January, doesn't really matter. JS January, JavaScript January, and Developer Tea. You have to have at least one of the JS January or JavaScript January tags and the Developer Teatag on your pen for it to be eligible. The only way that I know that you're actually entering the contest is if you use those tags. Make sure you do that. The winners will only be announced in the spec Slack community. If you haven't joined, it's 100% free. You can join at spec.fm slash slack. Of course, if you have any questions about the challenge, let me know. You can email me at developert.gmail.com. You can email any general questions to me at developert.gmail.com. I try to get to questions on the show. I'd love to have some JavaScript questions come in for JavaScript January. So send those questions to developert.gmail.com. You can also ask those questions if you go into the spec Slack community, which we already mentioned. Hopefully, you're already doing that if you are entering the JavaScript January competition on code pen. Thank you so much for listening. Thank you again to today's sponsor, WooCommerce, powering over a third of the internet's online stores. Go and check it out, spec.fm slash WooCommerce. Make sure you use the code Developer Tea for 25% off on WooCommerce.com. Thanks so much for listening and until next time, enjoy your tea.