Are you bad, good, better or best with Async JS? JS Tutorial: Callbacks, Promises, Generators
Skills:
JavaScript Fundamentals90%
Key Takeaways
Async JS programming using Callbacks, Promises, and Generators in JavaScript
Full Transcript
okay so in this video we're going to be handling JavaScript async operations which is uh really confusing to a lot of developers on how to do it in a good clean way and it can get pretty complicated you'll have to uh excuse me if I sound like I'm about to run out of breath at some point because I have a slightly bruised rib which means that I can't breathe in fully so uh but the code must go on so let's get into async JavaScript um and the 2C description of that is for those of you who are newer to JavaScript async is anytime you start something that completes later on JavaScript allows you to say hidden API and then not lock up your program you can actually say start the API and move on with my code and when the API returns our response say our tweets from the back end then we can continue processing code and we didn't lock up our application the users click events and drag events are all still going to get processed so that's what async means that's why JavaScript is awesome but it can also get complex so I'm going to give you four ways of handling this there's the good way the better way the best way and the awesome way which is the brand new way um and let's get into it this plunker address will be in the description so you guys can go look at this code later um and so here we go let's look at the first way of doing three async operations all in a row so I'm turning on the callbacks these are all all pieces of these code are going to do the exact same thing you can see again when I run it it fires there you go got profile got tweets got friends so every time something comes back it says this and then spits out its information let's look at that code uh for this example we're going to use jQuery because everybody knows jQuery if you're on the back end doing no JS the exact same principles apply um and so let's get into it this code right here is the Callback way of doing it it's a mess just opening this makes you want to run for the ibuprofen cuz you feel the headache coming off and it's only three operations it's not this super complex thing going on we're just doing three things in a row we're F firing a get to the profile. Json since we don't have a backend we can't really hit a profile API so I just have a static Json file here that will give us the exact same response um so we're getting the profile Json on success of that we are you know doing the two things we need to do saying hey got profile and spitting that out and then we're moving on we're starting up the next Ajax request which gets our tweets Json uh tweets passing it our ID um and so then success happens by the way this doesn't really do anything since we don't have a backend server but in theory the backend would take our ID and give us our tweets um but no matter what we do it's always going to give us this tweets Json um so then it fires this and then on the success of that we do our two things and we start up our third Ajax request and GH I just can't go on um it's bad for several reasons we've got the pyam pyamid of Doom uh wh don't want to Fork don't know why I hit the button we have the Pyramid of Doom going on right here as you can see Pyramid of Doom um and it's also called call back hell it's just a mess this is a very bad bad shape in JavaScript you don't want to see that um and then we're also having to handle our error here handles the error for this Ajax request here handles the error for this Ajax request and here we're having to handle errors at each step of the way this is terrible so let's look into how we can clean this up I'm going to kill this script turn this one on and the exact same thing just took place in the exact same way let's look at the code for this this code is called clean callbacks we can move a next step forward um by abstracting out the callbacks into their own functions so here we fire up our first Ajax and then we're going to for success we're going to run the G tweets function and for error we're just running the handle error function right away you notice it looks a lot cleaner it goes top to bottom in instead top to inside to outside mess so here we're able to go fire our first one get tweets get tweets does its two things kicks up our next Ajax which we'll F we'll do get mentioned user um and then handle the in any errors so you'll notice we're able to reuse our handle error function that's a lot cleaner and also it kind of just goes in order do this then get our tweets then get mentioned user and on the success of get mentioned user I didn't abstract this function out into its own we're just going to do our two final things and be done it's still kind of messy I still don't like this in a lot of ways it's just a lot of repeated code it's a lot of code we don't need to do let's get into the best way of doing this that is better let's look at best going to kill you turn you on prove that this code does the exact same thing yep let's look at promises promises are things a lot of developers don't understand yet so I'm going to show you the code wow that looks a lot cleaner that looks a lot better and it's also confusing if you guys don't know it so let's look real quickly over to this file where I explain what promises are um so every a promise basically represents a future value it's a standard Syntax for anything that has a delayed response JavaScript uses promises pretty much every good Library every Library that's built correctly every every framework that's built correctly should use promises should return a promise for anything that is going to start an operation and give a value later so Ajax starts an operation starts talking to backend and if you actually return the value from Jak Ajax say I do ver get profile then this is actually a promise or a deferred object get profile doesn't stand for anything yet it's just a promise it's a it remembers what the state of this Ajax request is so when the Ajax request moves on at some point that Ajax request is going to go um it's either going to resolve it say when the the get is successful it's going to resolve it with your profile um data and so then that gets fired to a then which we'll get into a second it's either going to resolve it or it's going to reject it if it fails it's going to reject it with your xhr objects your status your error everything you're used to seeing in jQuery so jQuery either resolves it or rejects it depending on what they do it will get passed to your then function basically if it's a promise it has a then function to it that's pretty much what you need to remember is so you can go get profile. thenen so thenen receives two things a success function and an error function if it was successful if it was resolved then it will run this with whatever it resolved it with as your argument right there if it was an error then it will run your error function with whatever the error arguments were so that's basically what a then or a Venable object is so when you run jQuery you can actually store that promise deferred Venable object as a name so there's some cool things that happen with this one is you notice as soon as you don't have to do success and error uh configuration you can use the simpler syntax of jquery.com function my error function now you'll notice right away this is not necessarily any cleaner or better than doing a success and an error function in jQuery if you're only running one thing there's really not much of a difference pass it success and error um in your object configuration up here and call it a day but where then really begin to shine where promises really begin to shine is when you have to chain things because uh the then object whatever you return from that gets passed to the next then you can do then do then do then and whatever this then function returns will get passed to the next then function and so on and so on the cool thing is is if you return another promise it's going to wait for that promise to fulfill before firing the next then function so we're going to run get profile Json it's going to wait even though we sent it a then uh do then it's going to wait until profile Json has gotten then it'll fire the then function uh passing it to profile and then we're going to start up our next Json and we're going to return that promise so then it's going to wait on that promise once that promise succeeds it'll fire the next then function with our friend here and another thing you can do is the error Prof the error uh functions will also chain on down so we all we have to do is add one error function here at the end so so if this first one errors it'll skip all the others and fire the last error function if this one errors then it'll skip down to the last error function basically no matter what you do the last error function gets the error now earlier earlier versions of jQuery I believe do not do this correctly but the latest version of jQuery does do this correctly so that's pretty much what A promise is uh you can see that I can also do something like this let's say what if you want to do several things at once every promise Library gives you methods to do multiple things at the same time so here we can say let's get profile let's fire that up let's also start the get friend process so they're both running right now and we can do a jQuery do when and put them both in so it's going to wait for both of these to succeed and then it's going to fire the function and you can see that it's giving us our profile and our friend right here and these are arrays of the arguments that would normally be passed to a success function so if you'll remember a successful jQuery thing passes uh it gives it your data and then it gives it your status and then it gives it your xhr object your jQuery xhr object so for the data we just want to get profile. Z so when they've both completed then we can get our profile right here and we can get our friend right there and then handle any errors that were passed on from either of these if any of them fails then we consider it a failure so jc. when is awesome uh Bluebird has that Q has that when has it lots of times they're like they're considered doall I believe Bluebird is is promised. all when is when.all um and I believe Q is q. all um and so that's pretty much what that is let's so let's look back at our promises JS um so you see here we're getting our profile Json and then we're running this do the two things we need to do and return the get tweets Json it's going to wait on that it's going to fire this then uh and then it's going to do the two things we need to do and return the friend Json promise so then it's going to wait on that promise and fire the last thing which is to mention that our friend has been received and then as the last thing here I'm going to do the handle error function so if any of these errors anywhere along the way then the error will get handled it will fire this handle error function so there you go that's promises it's way nicer way less code way more stable um but if you look at it and you're honest with yourself it's still kind of messy um it still is just a lot of thenen return. thenen it still feels like programming should make more sense so let's look into a new thing which is coming in JavaScript 6 es6 Harmon which you can actually start using today using Google Tracer um which will convert your JavaScript to es6 Harmony um let's look at generators you can see I'm going to turn this on the only thing you have to do to start using Tracer is you have to include Tracer the Tracer JavaScript in your page and then whatever JavaScript you enter you just have to give it the type of module so your browser won't run it but Tracer will pick up on it Tracer will convert it and then it will run it so let's look at generators. JS hold your breath cuz this is going to be really cool here we go profile there's this funky yield word in here um we're basically getting the profile and then we're doing something with it and then ver tweets equals get tweets and then do something with it and then ver friend equals that and then do something with it and you're done I mean look at that that is clean that is readable that is beautiful the only thing that might look confusing at first is this command cuz we're using a promis co- routine object we're using what's called generators es6 generators um and my next video is going to describe those in detail and show you how awesome those are and uh but basically you're able to yield this thing anytime you put yield it's going to wait on a promise so we can treat it just like a normal thing we can say their profile equals this and move on but it's actually going to wait for us to get the profile before moving on and then later on we can save air tweets equals this and it's going to wait for the tweets to actually fulfill before we move on the beauty of it all is it's still happening asynchronously it's not blocking your code it just looks like it's blocking your code so it makes a lot of sense I'll leave you there for that let's go into generators in the next video which comes out tomorrow um and the generators video we're going to cover a lot of these the cool ways that these ES six generators are working behind the scenes hope this video made sense for you
Original Description
The 4 levels of clean JS ASync programming: Javascript programming can get really ugly, really fast...but not if you know how to avoid "callback hell".
Code available here: http://plnkr.co/edit/1ArvFxI0gWmajTpDaOSB?p=preview
Also watch this video - ES6 Generators
https://www.youtube.com/watch?v=QO07THdLWQo
Level one: Programming with callbacks - you make it work, but it's ugly
Level two: Programming with abstracted callbacks - cleaner for sure, but still messy and way too much repeated code
Level three: Promises - much cleaner much more stable code, but still not as enjoyable as code should be
Level four: Generators - life is good.
This is a javascript promises tutorial / javascript generators tutorial. We're going to show the four levels and why each level is better than the one before it. Along the way, you should learn a decent bit about promises, and even some about generators.
-~-~~-~~~-~~-~-
Also watch: "Responsive Design Tutorial - Tips for making web sites look great on any device"
https://www.youtube.com/watch?v=fgOO9YUFlGI
-~-~~-~~~-~~-~-
Playlist
Uploads from LearnCode.academy · LearnCode.academy · 45 of 60
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
▶
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Web Development Tutorial for Beginners (#1) - How to build webpages with HTML, CSS, Javascript
LearnCode.academy
Web Development Tutorial for Beginners (#2) - Basic CSS - How to build a website with HTML & CSS
LearnCode.academy
How to create CSS Layouts - Web Development Tutorial for Beginners (#3) - with HTML & CSS
LearnCode.academy
Bootstrap Tutorial For Beginners - Responsive Design with Bootstrap 3 - Responsive HTML, CSS
LearnCode.academy
Angularjs Tutorial for Beginners - learn Angular.js using UI-Router
LearnCode.academy
CSS Tutorial - Web Development Tutorial for Beginners (#5)
LearnCode.academy
Node.js tutorial for beginners - an introduction to Node.js with Express.js
LearnCode.academy
Github Tutorial For Beginners - Github Basics for Mac or Windows & Source Control Basics
LearnCode.academy
Javascript Tutorial - Programming Tutorial for Beginners Pt 1
LearnCode.academy
Javascript Tutorial - jQuery Tutorial for Beginners Pt 2
LearnCode.academy
AngularJS Directives Tutorial - Part 1 - Demystifying Angular Directives
LearnCode.academy
WATCH THIS IF YOU WANT TO BECOME A WEB DEVELOPER! - Web Development Career advice
LearnCode.academy
YEOMAN TUTORIAL - Master Front-End Workflow with Yeoman, Grunt and Bower
LearnCode.academy
BOWER! - Streamline Web Workflow with Bower Package Manager
LearnCode.academy
Chrome DevTools for CSS - Better CSS Coding & CSS Debugging with Developer Tools
LearnCode.academy
GITHUB ATOM - Why Atom.io will be your favorite Text Editor!
LearnCode.academy
GITHUB PULL REQUEST, Branching, Merging & Team Workflow
LearnCode.academy
Pimp that Terminal - Add shortcuts and functions to your .bash_profile to simplify routine tasks
LearnCode.academy
jQuery Tutorial #3 - Writing Smarter, Better Code - jQuery Tutorial for Beginners
LearnCode.academy
jQuery Tutorial #2 - Event Binding - jQuery Tutorial for Beginners
LearnCode.academy
jQuery Tutorial #1 - jQuery Tutorial for Beginners
LearnCode.academy
Node.js MongoDB Tutorial using Mongoose
LearnCode.academy
Node.js tutorial for beginners 2014 - an introduction to Node.js with Express.js
LearnCode.academy
WEB DEVELOPMENT - SECRETS TO STARTING A CAREER in the Web Development Industry
LearnCode.academy
jQuery Tutorial #4 - DOM Traversal with jQuery
LearnCode.academy
jQuery Tutorial #5 - Building a jQuery Tab Panel Widget
LearnCode.academy
jQuery Tutorial #6 - Building a jQuery Image Slider
LearnCode.academy
jQuery Ajax Tutorial #1 - Using AJAX & API's (jQuery Tutorial #7)
LearnCode.academy
jQuery Ajax Tutorial #2 - Posting data to backend (jQuery tutorial #8)
LearnCode.academy
jQuery Ajax Tutorial #3 - Delegating Events & Mustache.js Templating (jQuery tutorial #9)
LearnCode.academy
jQuery Ajax Tutorial #4 - "Edit" modes & Better Mustache.js Templating (jQuery tutorial #9)
LearnCode.academy
How to put your website online - how to FTP to a domain & upload files to a webhost
LearnCode.academy
Basic Terminal Usage - Cheat Sheet to make the command line EASY
LearnCode.academy
SSH Tutorial - Basic server administration with SSH
LearnCode.academy
Vagrant Tutorial - Running a VM For Your Local Development Environment
LearnCode.academy
Sublime Text Favorite Packages and Workflow
LearnCode.academy
What Makes Javascript Weird...and AWESOME - Pt 1
LearnCode.academy
Javascript is Event-Driven - What makes Javascript Weird...and Awesome Pt 2
LearnCode.academy
Javascript Closures Tutorial - What makes Javascript Weird...and Awesome Pt 3
LearnCode.academy
FREE REST API - Practice Developing Javascript AJAX Apps with this API
LearnCode.academy
Javascript Scope Tutorial - What Makes Javascript Weird...and Awesome Pt 4
LearnCode.academy
Javascript Context Tutorial - What makes Javascript Weird...and Awesome Pt5
LearnCode.academy
Nginx Tutorial - Proxy to Express Application, Load Balancer, Static Cache Files
LearnCode.academy
Live Reload Sublime, Chrome, Anything - Fast and easy with Live-Server
LearnCode.academy
Are you bad, good, better or best with Async JS? JS Tutorial: Callbacks, Promises, Generators
LearnCode.academy
Javascript Generators - THEY CHANGE EVERYTHING - ES6 Generators Harmony Generators
LearnCode.academy
Web Development Advice - Interview with Dev Tips
LearnCode.academy
How the Internet Works for Developers - Pt 2 - Servers & Scaling
LearnCode.academy
How the Internet Works for Developers - Pt 1 - Overview & Frontend
LearnCode.academy
HAPROXY vs NGINX - 10,000 requests while killing servers
LearnCode.academy
Node.js Cluster - Boost Node App Performance & Stability with Clustering
LearnCode.academy
Web Dev Training with Treehouse
LearnCode.academy
What is Node.js Exactly? - a beginners introduction to Nodejs
LearnCode.academy
How to deploy node.js applications #1 - spin up a server
LearnCode.academy
Deploying node.js applications #2 - provision server & setup flightplan
LearnCode.academy
Deploying Node.js Applications - Deploy Node the right way - as an Upstart Service
LearnCode.academy
Mobile Web Design - Coding Workflow For Mobile Websites
LearnCode.academy
WHY YOU NEED A BUILD SYSTEM LIKE GRUNT, GULP, BRUNCH FOR YOUR WEBSITE
LearnCode.academy
GRUNT TUTORIAL - Grunt makes your web development better!
LearnCode.academy
STOP USING FTP! - How to Deploy with Flightplan over SSH
LearnCode.academy
More on: JavaScript Fundamentals
View skill →
🎓
Tutor Explanation
DeepCamp AI