« All Episodes

Async Code & Promises

Published 1/6/2017

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.

Transcript (Generated by OpenAI Whisper)

Hey everyone and welcome to Developer Tea. My name is Jonathan Cottrell and 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. And 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, right? 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. So 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. So you have a currently in progress and it can only hold one item at a time. And JavaScript allows you to do certain things synchronously. For example, setting a variable. And really 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. So what happens is, let's say for example, you run setTimeouts. And of course, there's plenty of resources on the internet that can tell you a little bit more about what setTimeout does. But setTimeout actually sends that call outside of your main processing... stack. So that main processing thread sees that you want to call the web API for setTimeout. That runs over on the browser. This is something that is not internal to JavaScript. It's external to your single thread. So once you call setTimeout, you're basically sending that out to the web API. Now when the web API is done with the timing aspect, so you say setTimeout, 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. And 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. Now 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. But 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. And the way that you manage it when it comes back, the event loop will grab that notification, effectively is what it is, that notification or that call from the queue that it has access to, and put it back onto the call stack. Now 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? Well 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. So you're saying something along the lines of let data or var data equals, and then you're running your Ajax requests, right? So in jQuery, it's $7, sign.ajax, you pass your URL, and when you try to use that data, well it's letting you know that actually that variable that you set is equal to an instance of a promise. And 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 that. So that's what you're doing. You're just going to run the call stack. And 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 timeout, and then you're passing in the function, you're adding a comma, and then you're adding your, the amount of time that you want to set that timeout 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, if you're 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, once you understand it. So how can we manage this? So how can we manage this? 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. WooCommerce is customizable e-commerce built on WordPress. They were launched in 2011 and acquired by Automatic last year. Go and 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. It's 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 DEVELOPERT. That's DEVELOPERT. That's 25% off that WooCommerce is offering. Then you can go again to WooCommerce for sponsoring today's episode. We're talking about how to handle asynchronous code in JavaScript. Really, 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. A promise is a particular kind of object. JavaScript actually has promises natively now, but there are other libraries that actually 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. So 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 calls, 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. And of course, you can respond to the failure state as well. On top of this, promises allow you to chain promises. So 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. And 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. And a perfect time for you to apply some of this newfound knowledge, hopefully you'll go and read some of this, some more documentation beyond listening to this podcast. But a perfect time for you to apply it is in the Developer T JavaScript January contest. Remember, this contest runs until about February 5th. And there's going to be at least six winners. All six will receive a year, a CodePen Pro for free. To enter, you create a pen on CodePen. And the rules are very simple. The pen needs to rely relatively heavily on JavaScript. This means more than just a few lines for code. You can use JavaScript as 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 CodePen, 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. And by the way, I incorrectly said that you would have to make it all in Word. You can still make it all one word, but you can also use spaces in your tags on CodePen. So JS space January, JS no space January, doesn't really matter. So JS January, JavaScript January, and Developer T. You have to have at least one of the JS January or JavaScript January tags and the Developer T tag 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. So make sure you do. And also, 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 at gmail.com. And of course, you can email any general questions to me at developerT at gmail.com. I try to get to questions on the show. And I'd love to have some JavaScript questions come in for JavaScript January. So send those questions. 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 CodePen. 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 developerT for 25% off on WooCommerce.com. Thanks so much for watching. Thanks so much for listening. And until next time, enjoy your tea.