Advanced Async and Concurrency Patterns in JavaScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
can y'all hear me alright awesome that was a pretty easy tech handoff thanks for coming tonight it's fantastic to be here my name is Kyle Simpson I'm much better known as getify on those interwebs Twitter github and all the other places that matter so if you find a place that doesn't have a getify maybe isn't that in I'm kidding but all those places you can find getify you can also find listed on my site and you can also email me get a fight maker square that's pretty predictable and I'll talk about maker square in just a second so maker square is a developer engineering training school we have three campuses Austin San Francisco and right here in Los Angeles Santa Monica area and we are the cream of the crop as far as it comes to developer training schools we have best-in-class curriculum we take you from being a junior level developer to fully intermediate level engineer and we get you a great job out of that and that's our mission that's our goal I joined about three and a half months ago now - as head of curriculum to lead the charge to make sure that we take our already fantastic curriculum and push it even further and widen the net of where we teach and how we teach and I am way up to my eyeballs in all of that and it's lots of fun but maker squares fantastic if any of you have any thoughts or questions about that you've wondered what training schools are about or maybe you're sitting next to somebody or you have somebody at home that's kind of been wanting to get into this whole development thing it wasn't really quite sure how to do it we at maker Square would love to talk to you and I've got a number of my co-workers from the Los Angeles campus they're here tonight so come and find us we'd love to talk to you about maker square in addition to that we would also like to offer as a special offer for those of you in attendance tonight and you can email us if you want to take advantage of this we have a course called maker prep which is basically a preparation course that gets you all those fundamental skills that you need before you can even get into a school like a maker square so we have a pretty high bar we like to think of ourselves more like the MIT of these developer schools it takes a lot to get in but we have courses to help you get there and one of those tools is called maker prep and maker prep is a fantastic school it's basically a one-month is that right one month in the evenings sort of course so you don't have to quit your job necessarily but you're going to to dedicate a lot of time and attention to that and we're going to be offering as a special offer tonight for those of you in attendance hundred dollars off the actual the normal cost of maker prep if you decide from what we talked about tonight that you like to join so reach out to one of us if you're interested in maker square I want to talk to us or ask us questions we'd love to talk to you about that in addition to the work that I do with Maker squared you a lot with open source development conference speaking and book writing so I have written a series of books on JavaScript called you know no js' the entire six book eleven hundred page series is available for free online at github so if you go to you know nodejs com it redirects to the github repo you can read the whole thing they've also been edited and published through O'Reilly so if you like what you see there I would of course appreciate it if you buy those copies of those books in particular I want to highlight one of the books the first book in the series is called up and going it's written from I don't know what happened it is written from the perspective of somebody that has never done a single line of programming before so it literally gets you up and going with the notion of what programming is and how to look at it from the perspective of JavaScript so if you're looking for those sorts of intro resources I get asked all the time hey do you know that intro resources there's a bunch of fantastic stuff out there a website that you may not have heard of before js4 cats JavaScript for cats calm you should totally go and check that out my book is also available for free even in the e-book the edited eBook form from O'Reilly and Amazon you can get the actual ebook for free on that so I don't want there to be any excuses for why someone wouldn't be able to learn and dig in to understanding JavaScript better in fact that's what my entire career is about is helping people move from the for lack of a better term move from the the good parts perspective of JavaScript which is it's poorly designed and there's this tiny subset that's good which I reject that notion entirely I think it's a fantastic language hopefully many of you are here because you at least believes to some extent the same but I wanted to move us beyond that whole good parts thing that's what got us all here but I want to move beyond that and go into the deeper understanding learning all the parts of the language that's what the book series is about that's what the trainings that we do at maker square about so in addition to our courses we also do corporate training we can come and train in York bunny and help you and your team learn better that's what it's all about is understanding JavaScript better so if you have any questions about that I love you to jump in before I talk before I do my talk tonight I want to make a quick mention of something and any time I'm given an opportunity a stage to talk to people I find this to be very important so please just indulge me for just a moment I want to talk to you just for a quick brief moment about what I call privilege awareness I look out in the crowd and I see a pretty good mixture of folks but I see an awful lot of dudes that look like me to be completely honest and I don't find that acceptable that no matter where I go in the world and no matter what types of events I go out we don't see enough inclusivity and the sorts of things we do and this is not a knock on any individual person or any event or anything like that but it's just to simply say there are structural reasons why our industry is not as inclusive as it should be you notice I'm thought I'm talking about inclusivity rather than diversity diversity is something that happens when you become inclusive so we should be focused on inclusivity of everyone and there are things that I have had in my life that have been privileges that have allowed me to get to where I am and other people getting to the same part have same spot have had to work a lot harder and it's not fair I have a daughter and a son and I don't want them to come up in an industry where my daughter has to work harder than my son where she's going to be second-guessed so the fact that I'm white and I'm male and I'm heterosexual and I'm an American and I'm employed and I'm Caty those are my privileges so I'm simply talking about myself to say we need to be aware of our own privileges so that we can be more empathetic of other people that have a more difficult path to get to the same spot so I don't have a solution to the problems but I know it starts with talking about it more and I would like for each of you to take a challenge away from this to ask yourselves what is my privilege what is my story and what is my privilege and talk about it more so I'm given an opportunity to say it and I think we need to declare our privilege so that out of the way thank be surprised I actually get kind of get a mixed reaction sometimes I get a warm reception sometimes not so much to that but I think it's important unless all right so that out of the way I'm going to talk tonight about concurrency in JavaScript and that's closely related to this notion of async programming so we're going to talk about that the the stuff that I'm going to talk about tonight kind of the highlights and some of the advanced stuff from a two day training course that I give on asynchronous programming a deep dive so I'm trying to present that to you and I've been given like 25 minutes to present to you what I normally do in two days so I'll probably be able to turn this down to about three and a half hours or so I'm sure you all are excited about that now I'm kidding of course it'll only be two hours but let's talk about concurrency in JavaScript to quickly make you understand what concurrency is we need to actually take a step back and talk about those terms async and parallel because they're often confused as being the same thing and they're really only the same thing if you really squint at it from a long distance away there's some important differences between async and parallel so async is kind of like when there's like imagine at a theme park and you're waiting for a roller coaster riding there's this long line and you all show up at the you know you get to the front of the line and there's 30 seats on the car but they're only letting one person on to the roller coaster at a time so at any given moment there's only one thing happening parallelism is when 30 people get on to that ride and all 30 of them experience the exact same thing at the exact same time so where does JavaScript fit we know javascript is async but javascript is not parallel our JavaScript code runs in a fundamentally single threaded event loop environment which means at any given instant only one of our functions only one of our lines of JavaScript can be running that may seem like a tremendous limitation but it's actually a huge freedom it's a freedom from having to manage all the complexities that parallel programming huh and if you've worked in a threaded environment before you know all the complexities of mutexes and semaphores and all of this other crap that I don't even want to say that's the life that you live when you work in one of those languages so it's tremendous power but also tremendous overhead in terms programming very hard to get threaded programming correctly fact I'd probably assert that virtually all threaded programs right now that have been written have bugs in them because threaded programming so hard so we're not we don't have to deal with those particular problems in JavaScript but we actually have a different set of problems concurrency doesn't mean at any given moment something is happening like at any given instant two things are happening at the same time but if you really look at what concurrency is about it's about two higher-level sets of tasks occurring within the same time frame so rather than looking at an instant of time and saying there's two different cores running two different actions what we would say is there's two higher-level actions that are happening in the same period of time so we might visualize those two higher-level things as the blue and orange that I'm showing here on the screen and I've broken them down into numbers to illustrate the idea that a higher-level task is composed of and I'm making up terms here micro tasks so we have this macro level task and a micro level task the numbers represent those micro level tasks so if the yellow orangish color represents making an AJAX call and receiving a response back and the blue represents scrolling the page and repainting and updating the location on the page those can be comprised of individual steps that may occur so if I were to pick the most naive scheduling of this program and for our sake for our intents and purposes let's say that each one of these micro level tasks takes one second to complete then the entire system is going to take seven seconds to complete in the most naive way to schedule that is to simply do all of the orange and then all of the blue or all of the blue and then all of the orange and if you thought about it in terms of not being able to break down into micro tasks that basically would be your only option and what you'd see is wow this system feels really slow because I click on the button to fire the Ajax but the button doesn't repaint until four seconds later because I can't repaint the screen because something's blocking it so instead what we do is break down our programming tasks into as small a pieces as possible as little blocking as possible these tiny little pieces can be ordered they can be scheduled in a different way for example like this and that animation took me about two and a half hours to get just right in keynote I'm sad I didn't get rounds of applause out of that but nonetheless we ski thank you such it such a cheap speaker ploy to get laughter and clapping I'm bad at that we scheduled this differently and the system is still going to take seven seconds to complete but now the perception of the performance of the system is drastically different because from a high-level perspective they appear to be happening at the same time this is a concurrent system this is not a parallel system it's a concurrent system so our task as programmers is to understand concurrency it's the cards we've been dealt in the language that we've chosen to write in we need to understand and manage concurrency and by the way the complexity that we have we don't have to deal with threads with the complexity that we have is to figure out how to coordinate our concurrency because you might make several requests at the same time and it's okay for them to happen in parallel that's how we always say it you ought to change the saying they're happening concurrently but we always say in common parlance where we say they're happening in parallel these two different Ajax requests and this one database requests they're all happening in parallel well that's all fine and good that's easy to do the hard part is to make sure that they're secret the responses to those things are sequence correctly because you may need to sequence those three have to finish before the fourth thing can start because it needs information from the first few so it's the coordination of concurrency that makes our job difficult and we have a number of different ways to coordinate concurrency built into the language is the humble call back and in my trainings I would go through all of the history of how the callback works and we dissect callbacks and look at their their practices and patterns but we build from callbacks into a notion of promises how many of you have heard of promises now okay great fantastic so a quick primer on a promise here's a quick little idea of what a promise might be and this is just kind of like a review of some ideas from promises and generators so this talk is not really about them but I'll make sure you understand them before we go to the other stuff so promise it's like when I walk up to a counter at my favorite fast-food restaurant and I ask for a cheeseburger and the lady says that'll be $1 thirty-nine so I hand her some money and I've started a transaction what I'm expecting in response as a cheeseburger but that's not often what she hands me what does she give me instead a receipt with an order number on it it's a promise for a future cheeseburger so now I can take this receipt and start to think about and reason about my future cheeseburger I don't have the cheeseburger yet but darn if I can't think about it my mouth starts to water to think about this cheeseburger so I step back and I'm waiting for those magic words order 3:17 and a big smile on my face I step back up to the counter I exchange my receipt for my cheeseburger that's what a promise is it is a representation of a future value it is a container that we wrap around a value where it makes it so it doesn't matter if the value is here or not we continue to reason about the value the same way regardless of whether it's here or not that's a real crash course metaphorical idea for what promises are they are a container around a value that eliminates time as a complexity okay that's one of the things that makes them so powerful it's not about the API there's a bunch of people out there right now that are like the counterculture like ooh boo on promises because all they focused on was whether the promise API was any good and it's a it's okay it's better than what we had before the promises aren't exciting because of their API promises are exciting because of their concept it's a truly powerful concept to have a time independent wrapper around a value and whether they botch the API or not is actually a secondary concern the important thing is how do we use that tool so promises are a way to represent something that may happen right now may happen in the future but I can compose these things together as if they're all here right now and it doesn't matter that they're not that's how we manage the concurrency with promises when I make an AJAX request and an AJAX request and all I care about is that both of them finish I have promises that represent those responses and I compose the promises together and I let the promise take care of the details of it's not here yet and on the other end out spits my value from both of those having finished so I don't have to worry about that coordination I use promises to coordinate so that's our first basic level understand concurrency if you're not dealing with nested callbacks you level up your game to understand how promises help you manage concurrency that give a trustable auditable mechanism for concurrency management great so what about generators actually generators really don't have that much to do with concurrency but they are really important side effect that we can use in our programming because they solve this other major problem in our programming which is that to express asynchronous programming is fundamentally non reasonable we can't reason linearly about our code when we have to jump all over the place and whether you knew it or not your brains are fundamentally at the highest level of cognition very synchronous and single threaded you process through your steps one at a time you planned out your day very sequentially well it sucks when we our brains work that way but that's not how the code that we're using works and I have this theory it's untested but I'm pretty sure it's mostly true wherever there's a divergence between your brain and the JavaScript engine that's exactly where bugs start to happen right you want to look for bugs find places where your brain doesn't work like the engine so if we have this problem that our brains work differently we need different programming patterns and generators very briefly are a way to take what is fundamentally the necessity to orient different actions but one right after the other basically to coordinate the responses to concurrent behavior it's a way to do that in a very synchronous sequential looking fashion so we get synchronous sequential looking code even though it's fundamentally still asynchronous and performant it's like the Silver Bullet them putting the best of the both worlds together so we have these two things promises and generators and they are the building blocks of next generation asynchronous programming if you don't fully understand how that pattern is going to improve your code that's the place to start leveling up it'd be nice if somebody would write a book about asynchronous programming patterns and help you figure all this stuff out somebody should do that promises in generators so let me quickly illustrate and some code promises and generators I've just got a simple scenario set up here I got a fake Ajax call let me make that bigger so some of you can see it easier in the back I got a fake Ajax utility and it's hard-coded to pretend that I can ask for these three URLs file1 file2 and file three so here's my setup I'm going to ask for all three files in parallel I'm going to ask for them in parallel aka concurrently so they're going to complete it the same in the same timeframe right I'm not going to wait for the first one to finish until after the second one finishes or whatever so I'm going to do so in parallel but I want to coordinate the responses so here's the coordination I want I want to print the responses as soon as they come back however one additional constraint is I want to make sure that I don't print too before one so if one comes back right away let's print it and then we can wait for two and three but if two comes back first don't print that yet because one hasn't come back this is actually a state a restatement of a pretty fundamental pattern in the UI world we need to do multiple things in parallel but coordinate their responses but we do things ASAP because that looks more performant to the user okay so how do we do that well we could construct a really gnarly set of code around callbacks and things like that but what do we do with promises how do we express this with promises so if I started out with this get file function I would need that get file function to return me a promise and then I would want to compose those promises together so this is not taking a callback it's returning a promise that's fundamentally how we make an asynchronous action promise aware so this is how I do it I return a promise from that get file function and you'll notice that it uses my fake Ajax under the covers and it uses one of the two callback continuations to signal it the promise is completed whenever the Ajax finishes so from the outside world I simply call that function and I get back p1 p2 p3 I get three promises back that's the easy part the more complicated part is to think how do I sequence the responses to those promises together to give me the properties of the system that I asked for well it turns out is actually not that complex we chained promises together I start out with p1 and when p1 completes I want to output what it's got weather that takes a fraction of a second or whether it takes ten years I want to print it out as soon as p1 comes back and then I want to wait on p2 there's only two possible scenarios either p2 has already finished in which case we're just going to keep going on or it hasn't finished yet and we'll just keep waiting but you see the value of composing these promises together in a chain is that I don't have to care about that detail because the promise is a time independent wrapper it manages that state internally so I simply chain my promises together and I get the properties of that system that I'm asking for so you say well that's all well and good and I actually a couple of years ago so we started writing all of my code as promised James it's all well and good we've got promise chains that's way better than nested nested nested callbacks right well it turns out that's only half the solution the other half is to make this more fundamentally sequential looking so that it works the way our brains work and that's where generators come in so here's the same program but approaching putting promises and generators together and my solution is still to ask for the three files in parallel but notice how I sequence the response I call this yield keyword inside of a generator which is a special function I can literally locally pause the function to wait for an arbitrary amount of time for some promise to finish inside of the function everything stops like it's a blocking program but outside of the program everything else continues to keep going that's the magic of generators they have locally possible stacks so I just simply say yield where I want that pause point to occur and I don't have to manage the complexity of how those compose so now I rewrite all of my code using generators and promises together so that's if you don't know that stuff yeah that's where you got to start you got to jump in to promises and generators but actually that's just review stuff that's not even really what I wanted to spend some time talking about tonight what I really want to talk about is some next next next next level stuff it's the stuff that the leaders of frameworks and languages are starting to talk about right now these higher-order patterns for concurrency so I want to talk to you just a moment about a fundamental shortcoming of the promise promises are awesome but there's one particular thing we do a whole bunch in our programs that promise is actually pretty much suck out and that thing is responding to events so let's look at this program this program is I start out a promise I'm creating a promise wrapper and inside it I set up an event handler on a button and yeah I'm using jQuery I'm cheating because I just need shorter code for the slides doesn't matter what you use but I'm setting up a click handler for some button and fundamentally when you click the button the premise of this program is that it's supposed to resolve the promise and then print out the class name down here at the bottom the next to last line which is awesome for the first time you click the button but fundamentally there's a problem here because promise is one of their characteristics is they can only ever be resolved once so this is going to work great for the first time you click the button and every other time you click the button nothing's going to happen because the promise has already been resolved oh oh we need some higher-order pattern for managing concurrency when there's a stream of events it's not just a single thing like a single Ajax request but there's a whole stream of events we have data streaming from the server we have click events in our UIs whatever you think of that happens in your app even single level events can be thought of as streams of events they decompose to the same notion so we need some higher-order pattern and one of the common patterns that's starting to get more popularity is called reactive programming so we could reorder this program by the way we could invert the program and put the promise creation inside of the button and you'll notice that basically I have to do not only the promise creation but I have to also define the promise response inside of the promise creation so this will work but now we've inverted our code and created a a violation of separation of concerns because the creation of the promise and the consumption of the promise have to happen in exactly the same code that's an oops that's a bad design pattern that's a code smell promises are not up to the task by themselves we need higher-order patterns so one of those higher-order patterns is called concurrency is called observables also known as reactive programming so there's a huge library that is it's got a lot of popularities from Microsoft called Rx and it's been ported to like fifteen or twenty different languages it's awesome it's also gigantic it has hundreds of methods on it the documentation is pretty stout you probably should have a PhD before approaching it because I still get confused reading some of this stuff so is there a way to understand and in this like the simplest sense like what's my hello world for understanding this thing well unobservable is fundamentally an attachment to an event stream that produces a promise for each event it's taking care of that complexity and it's harder than you think it is it's taking care of that complexity for you such that I can define my responses to an event as a chain of promises and not worry about that whole like create the promise thing so now I get the separation of concerns I can declare my stream in one location that is my producer of events and I can declare my consumer in an entirely different place and the consumer simply declares what is my response so I make an observable and they'll it'll have a method in their API called from event so you have a standard Dom event attachment and it'll produce a stream of events suitable for you to subscribe to in reactive programming sense so here I have like map and filter it's kind of like synchronous steps and stuff but notice this distinct until changed this is what makes observables different than just a fundamental synchronously chained API like a jQuery is that actually the entire chain is kind of like a promise chain so the entire chain can be asynchronous as necessary distinct until changed does not move on to the next step until there's a been a change in value that it does what it says on the on the on the box it's distinct it's waiting for a distinct value and then once it's changed it's waiting for the next distinct value so if you have a stream of a whole bunch of xxxxxx it's only going to fire once until it gets a Y and then it's going to fire once for the Y and then it's going to go back to X and only fire once so it's a way to deduplicate a stream of repeated events but fundamentally a chain off of an observable is a way to subscribe asynchronously to a stream so that's great but that API is pretty complex it's like 150 K now in all fairness they're doing a rewrite to make it modular and where you can be able to choose but now you're going to have like 250 API methods to figure out which ones you need to pick and choose from it's a big task I'm not saying it's bad it's a big task so I set about to try to create the small proof-of-concept for what reactive programming would be like and I attached it to a library that I had already written for asynchronous flow control and that library is called async once it's the word async plus the word sequence mush together because there were no other good names on NPM basically okay they're all the good ones have been taken so async once right now I'm not even going to spend any time trying to sell you on anything once you like it you don't like it I don't care but it is a library that brings together all these different programming patterns in one tiny library it's like 7k it has reactive programming it has CSP which we're going to talk about in a minute it has promises and callbacks and thunks and generators it's got it all in one spot so you don't have to go learn a whole bunch of different libraries it's the 80 percent case that helps you learn these principles I designed it to help make this stuff easier to teach so if you're looking for a place to learn maybe that's a place to start but how to async ones do it I call these reactive sequences so I came up with a different word because I didn't want the Microsoft folks to get mad at me and you know claim trademark infringement or anything I'm kidding but I called it reactive sequences so you understand that it's a smaller subset of the same concept how do reactive sequences work pretty much the same way you subscribe to an event stream and then you declare a chain of potentially asynchronous responses and that chain can include promises and generators and other observables in fact one of the coolest things of thing about observables because they're streams is we can actually do stream oriented events we can compose to smaller streams of events into one synthetic higher-order stream so here I've got a stream of key presses and clicks well what if I wanted an event that represented when both of those happen at exactly the same time I'm simply called all so dot all waits until there's an event from both queues and then it fires a synthetic event to let you know both of them have happened dot Eddie says I'm going to fire as soon as either one of them fires so we have these ways to compose streams into higher order patterns and spawned to the asynchronous city of our programs so that's a real quick primer on observables and if you're looking for the next place to go after promises and generators you should learn observables there's a pretty good chance something like this is going to land natively in the language sometime in the next year or two all right so the last thing I want to show you and I'll end with some code but real quickly I want to talk to you about a different pattern this isn't getting any kind of press it's actually a really old idea invented back in the 60s really smart guy he invented this idea called CSP it stands for communicating sequential processes it's a different way of organizing how we respond to concurrency and it models independent things as totally separate processes and these processes operate independently and the only way that they coordinate is when they need to synchronously message each other so imagine thing a over here is spending doing its thing and thing B's over here and at some point the two of them need to exchange a message so they both get to that point and they wait so he gets to this point and she gets to this point and now they can send a message and then they go back to being independent and we use a channel to do that so it's like blocking on channels that's how CSP works okay so this is what it looks like looks like a generator right because that's how we model CSP and JavaScript is to understand generators because generators kind of work like independent processes that can be paused and resumed so I'm waiting on the put line for I'm saying yield put I'm trying to put something on to a channel and there has to be somebody on the other side ready to take it and until somebody's ready to take it I'm going to be blocked or if take happened first I'd say I need to take something from the channel and I could wait until somebody was ready to put something on the channel so both of them have to get to the point where they're ready to exchange and then they unblock each other now this can actually be modeled not just across different parts of JavaScript you actually model this remotely working on a research project right now building a library that allows you to remote your CSP concepts across web workers or across browser windows or across the wire from browser to server it's the same notion just simply blocking and waiting for a message CSP is where I think the next generation the next generation the next generation of JavaScript program is headed it's incredibly powerful it's got a lot of places where it's even more powerful than observables it's not necessarily the Silver Bullet but we've got a lot of work to do to research this and make this go and by the way this isn't just some weird invention of mine it was actually the model for concurrency in the go programming language as well as closure and closure scripts so there's some pretty smart people behind the CSP model all right this is just a quick example it's a silly ping-pong example so I have three different instances of generators here and each one of them is pretend it's running independently and there's pretending to play a ping-pong game two different two different processes or ping pong back and forth which it they're transferring the ball by waiting and then sending the ball to the other person so it says ping pong ping pong and then the table says times up games oh okay so you can model higher-level concepts in your user interface as independent promises processes that communicate with each other all right so my library async once also manages that stuff and that's you notice it looks basically exactly the same I have the same API so you can do CSP directly in that library as well so what I want to finish with is a quick demo that is actually a repo it's an ongoing project of mine it's called a tale of three lists so I'm going to pop this thing open and it's free reap obviously up on github that you can go and look at it's a demo of a whole bunch of event oriented stuff that's happening so it's a slightly more sophisticated hello world kind of thing with two different lists and I'm going to show you how this works I'm gonna actually run the demo here for just a minute what I I don't even have Wi-Fi that's awesome how do I get on Wi-Fi all right I should have remembered I needed to be on Wi-Fi hopefully this doesn't take too long all right so while that's connecting let me just talk about it there's a producer of items it's like faking like items coming from a list and then I have two different lists that are consuming that at different speeds so there's sampled consumption of these threads and then I'm allowing you to click on different items in the list and move those items over into your own and then did I type it right I miss the knell there we go awesome they're gonna have to cut that part out of the video otherwise they're going to change their password and then there was no more bandwidth all right let's see if this connects real quick so I can show you this demo and then we'll finish up all right here we go so what's happening in the background is that it's going to start producing these items at a pretty rapid pace and then I have two different lists that are consuming that at different speeds which is why you see the items coming in now I can start to select items from this and you'll notice they're animating so a synchronicity is happening both in the back end as well as the front end and I'm managing all of these events now this repo I reimplemented this exact same demo and you can pause the different lists irena implemented this exact same demo seven different times using seven different concurrency management patterns from basic callbacks all the way up through promises and generators all the way up through the reactive program that we just talked about as well as CSP so you have seven side-by-side code bases to compare the relative strengths and weaknesses of these different patterns using a somewhat more sophisticated demo so how many of you have heard of to do MVC before okay you know to do MVC is like how we compare all these different frameworks I kind of think of this project is like the two MVC to do MVC of asynchronous programming and I invite other people with different libraries and patterns to try their hand at implementing it so we have side-by-side comparisons and we can learn better how this stuff works so real quickly as I finished up I know they're about to throw me off but real quickly let me just show you some of that code so here's the user interface for the reactive sequence and I have a function here called toggle feed which looks like a straight-up regular event handler because it is it's attached to an event stream so my event stream might look like this I'm saying email dot on so I'm saying I'm going to listen to some clicks and I'm going to turn this sequence of events that are coming in into a reactive sequence that I can respond to so async lets library we just say a are done of to give ourselves a reactive sequence and then we push events into the queue and we can consume events off the queue it doesn't get it this is about as simple as you can get but now we have reactive sequence that's attached to our dumb clicks so I can listen for those Dom events and respond to them so I can have higher order things like here's here's my feed so this is my this is how I'm sampling the feeds at different rates I set up my set up an interval and I'm pushing something into my reactive sequence at that slower rate so I'm pulling stuff off of some other stream and throwing away stuff that I don't care about and pushing the last message on so we can compose really complex UIs in terms of higher order streams and the codes got way more details about that so I'd encourage you to look at streams finally the CSP stuff that I just talked about there's toggle fee but you notice now it's a generator and you notice one important thing it has a while true in it what I love to say about generators is they're putting the wild true back into programming so we all know wild true is like the evil of all programming right because you kill your program well when there's a paused point inside of your wild sure it turns out that's exactly what you want you want this thing to basically run forever for the entire length of your program and it'll pause until somebody gives it some stuff to do and then it will resume and then it'll pause again and resume and pause again and resume so I have a wild true loop here and you'll notice that I simply yield on putting a message into a queue so this is how I'm pushing out feed items and I'm yielding to put so I'm only going to run when somebody is on the other end ready to take the item off the channel now I wish I had two full days to teach everyone Here I am going to be filming this workshop that I'm talking about today I'm going to be filming that for front-end masters I got a bunch other training up there so you'll eventually be able to get the longer form version of that but I hope in just this few minutes what I've shown you is there's a whole lot more to asynchronous programming than the stupid little callback there's a lot more sophistication now you may be wondering why do I just get excited because it's a new cool shiny thing for me to play with here's why this is why we do any of what we're doing in program this is why I do any of what I do to teach programming the code that you write you may think that the code that you write is all about the computer it's all about instructing the computer what to do I have seven different programs that give it exactly the same set of instructions the same ones and zeros in fact there's an number of programs that can do that the computer almost doesn't even care about your code so if the code that you write is not primarily for the computer who's it for it's for other human beings code is fun fundamentally first and foremost a means of communication with other people your teammates other people that consume your code and your future self so what we should be seeking to do is not fundamentally do stuff that we could never do before I haven't shown you anything new that you could not have done before every single thing here you could have done before what I've shown you is how to do it in a more reasonable understandable learn about and teachable way that's why es6 is awesome and that's why it matters that's why asynchronous patterns matter because they make us they allow us to write code that is more expressive more learning and more teachable that should be our goal when I refactor my code that's what I'm worried about how do I make my code make more sense now how do I make it do something more exotic how do I make it make more sense so I hope if nothing else I've inspired you to go out and figure out how to make your code more readable understandable learning and teachable there's a lot of great tools out there hopefully I've provided you some good materials to jump into that so I'll finish with my final slide to say thanks very much I probably have run over my time for official questions here and discussion but going to be around the rest of the evening so if you have any questions about this stuff feel free to come up and check that out check out the books and ask us about maker square we'd love to talk to you about making your code better
Info
Channel: Hack Reactor
Views: 122,831
Rating: 4.6266665 out of 5
Keywords: makersquare, coding, bootcamp, kyle, simpson, kyle simpson, javascript, js.la, getify, async concurrency patterns, async, concurrency, javascript patterns, advanced javascript
Id: Qg1SvpIau6U
Channel Id: undefined
Length: 39min 42sec (2382 seconds)
Published: Wed Mar 02 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.