Part 2: JavaScript the Hard Parts: Promises, Async & the Event Loop

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] let's move right along here we are finally ready to introduce some things that we haven't talked about yet that you're probably all here for so this whole process here is pretty great once we know how it works right we're able to do and accomplish all of the goals that we set out to we can delay functionality without blocking our main thread and we can run functionality delayed functionality knowing that this long task is complete great but there are problems with this approach right the biggest one is that most people don't know how it works right most people look at something like set timeout think that it's regular JavaScript and write it in a way that doesn't actually work for their use case right we also get into this point of potentially getting into what we call callback hell right let's think about what happens when this set timeout the callback for this set timeout is print hello and let's say inside print hello instead of just a console log we have another set timeout that then runs block for one second right something like that and maybe we have a weight of you know a thousand in here or something like that right when we start doing this now we have a callback inside a callback inside another callback so every get into these things called callback health so that's not great it's not really super clear what's going on here the biggest thing is that set timeout looks like regular JavaScript right that's why most people don't know how it works because why take the time to look into the documentation for set timeout when it's pretty obvious what it's what it's used for and it looks like regular JavaScript so no need to worry about specifically looking up the documentation it's not a great track but it's what most people do right most people look at stuff and say can I reason about this before they go and you know look up the documentation for it fair enough right we want code to be self-explanatory and easy to read through right but it is a problem and it's really a problem to think about okay I've now I've now sent this task out to the Web API and I've just passed it this function definition and I'm just gonna hope that at some point that function definition makes its way back in the JavaScript and gets invoked in JavaScript somewhere right but it's not explicitly clear how or when this print hello function is ever going to be used right so this was the way that we accomplished a synchronous activity for a long time not just with set timeouts but with other other what we what I would call facade functions right or cousin calls facade functions like set climb out these things that actually send tasks off to the web api there were other functions like that that would send out requests to Twitter for example and do similar things we'd pass it a callback function and hope that at some point after we got that tweet from Twitter that function would run right but the creators of JavaScript when they were writing the es6 the yes six spec were like okay this is something we're doing more and more often we're taking more and more advantage of this asynchronous functionality let's build some syntax in JavaScript and some mechanisms in JavaScript they're gonna help us with this problem so now we have something called promises promises are awesome before I introduce more about promises and the mechanisms within them let's just start going through and and and just start diagramming through this code because it's a lot more clearer when we start diagramming it the benefits that we get out of these promises right but quick thing right basically promises are just two-pronged facade functions right they both send tasks out to the web api we're still using the web api here we're still pass the office delayed functionality somewhere outside of JavaScript however we get a bonus inside JavaScript we get immediately returned to us an object a placeholder object or a promise object right is known as a promise object right that gets immediately returned in JavaScript which is basically a promise of data to come later right it's a placeholder for whatever that delayed functionality returns or whatever that long task returns right so let's take a look this is this is the code that we're gonna run I'm just going to run it through it here real quick because it's a little small on the screen down here we have this function at finishin display we have this we have this variable declaration where we're invoking this fetch function then we have this very interesting line here which is future data then display we're going to spend a little bit of time talking about what this line here does and then we have our handy-dandy console log of me first right so let's run through this line by line like we do Susie you're my quirks tell me what happens first line of JavaScript here so we have home we have the function display that's that's going that's going to be added to their execution context absolutely to the global memory right yeah just that function definition what are we gonna do on our next line and and then we have a constant fetch data so I can't really see yeah yep so we have a Const future data and future data is going to be set to what a fetch function a fetch function and then that takes a takes a URL yeah and so since we're invoking a function here right in our global memory that variable is just gonna be undefined for right now right we need to actually fetch and invoke this fetch function with this with this URL that's here right and so quick thing right while this might look like a regular old JavaScript function here again this is one of those facade functions so not only is it going to send some data out to the web api right and just for the record this is sending out to the web api but we're not using time-out here instead we're using something called xhr or XML HTTP request to be able to send a packet of information out to a server somewhere and get some hopefully get some data back from it so we're still passing this task off to the web api you're using specifically the xhr feature but in JavaScript now we also get something in return I'm not going to use pink that seems silly let's use blue okay we get something back in JavaScript here this is one of those two pronged facade functions so not only do we get that not only do we send that task off to the Web API but now we get this object back it's a promise object so immediately returned to us after invoking this fetch function we get an object back so instead of future data being undefined for a long time until we get some data back or something like that right we now have future data is an object and I'm actually gonna make this even bigger so that we can see it and add some properties to it along the way so this is the object that gets immediately returned called a promise object and it has a ton of properties on it that are baked into this promise object we're gonna talk about a few of them tonight there are many many others that you can research at your leisure the few that we're going to talk about tonight are status so the status defaults to pending right this is a pending promise we don't actually have any returned value yet it hasn't been fulfilled or rejected it is pending pending some data coming back right then we have a value and here is where we keep that undefined right so the value of this promise is currently undefined because the status of it is pending we expect that when the status changes we will probably have some value that gets added here updated here cool for now that's all we're gonna care about we're gonna add more pieces on to this as we keep diagramming three-dose but for now oh these are the things that we care about so we immediately get back in JavaScript this promise object and our thread moves right along let's say here still at one millisecond we'll go out to the web api now and talk about what happens out here because it's slightly different from what happens with the timer but not too different right so now out here with xhr we are still checking if this is complete and we're still going to do something when it is complete you you now what we're going to do when it's complete is a little bit different so xhr works like this xhr sends out a little package write a request out to in this case we passed it a Twitter URL so it's gonna package up that request send that request out to Twitter and then it's going to wait right it's gonna wait for something to come back from Twitter but that might take some amount of time so at one millisecond when we come out here this is not yet complete right nope we still don't have data back from Twitter what we're gonna do on complete we'll talk about in a second but for now out here in web browser API land we are sitting here waiting for Twitter to come back with some result all right then tell me brenn what are we gonna do on our next line what's the next line that we're gonna hit in JavaScript after we hit this constant feature data we are going to go to the next line which is GG data dot then which is a function we invoked from the future data object yeah and what are we gonna pass it we are going to pass it display which is the function definition we stored in global memory absolutely thank you so much bread we're going to pass it this function definition for display so let's talk here right we are invoking a method called then right we expect then that whatever future data is which we said right is an object has a property on it with an A with a value or a property with the key then and a value of a function definition surprise surprise that is very true right part of this promise object another property on this promise object that's baked into it what that we get immediately returned to us is a method called then this none method does a few different things but what its main purpose is is to attach delayed functionality to this long task so right here we're seeing one we're seeing another additional benefit of this promise object right not only do we have a way in JavaScript of seeing sort of the status of our promise the status of our a synchronous activity but now we have a way of decoupling the asynchronous task from what we want to do after it's done so we have a way of saying okay we want to get tweets we can write this function to get tweets but we can separate it from what we want to do after we've gotten those tweets or what we want to do if getting those tweets fails right and we can do that by using this then method that's available to us on this promise object I'm gonna delete within out of here it's not gone anywhere I just want to use this board space for something else because what this then method does it takes this function definition that we pass it as the first argument it wraps that function definition with some specialness right some special promise permissive ID functionality and it basically adds that definition that function definition to an on fulfillment property that also exists on this promise object this is getting a little small here I apologize for that so on fulfillment is another property on this promise object that we care about its value starts out as an empty array what we push into this on fulfillment array are function definitions that have been specially rapped by this then method and it's basically saying this is what we want to run as delayed functionality if this promise is successfully resolved in this case that promise is getting tweets so if we successfully get those tweets we want to then run keep moving we then want to run this function definition that we've passed in here which is for display quick sums on that how do we feel about this sweet all right so then haha so then we have finished running this then method our thread is ready to move on let's say two milliseconds we're ready to move on again what are we going to do next uh Alex are you there no Alex I'll come back to you let's see uh Peter what are we going to do next oh you're muted that's sorry noise we're gonna creep yeah happens often we're going to create say we're going to go down to the console dot log line we're going to create a we're going to create a new local execution context and push that function onto the call stack absolutely and I've just realized I've made a grave error and that global was not on here that's okay on there now it's been on there let's pretend it's put on there the whole time so yes we push console log on to the call stack right great we get a new function level execution context I'm gonna make it much smaller than that because we're gonna be hurting for board space here in a second Suites console log is going to run over here in our console at around two milliseconds we should see me first all right cool what happens when we're done running this function then Peter ah the little uh you're gonna local execution context is gonna is going to be erased you're going to deallocate that memory and then Compostela logs gonna get popped off with a call stack beautiful absolutely thank you Peter sweets no and around three milliseconds here then we're back out here console dot log all done great do we have anything else to run in our global execution context anymore spoiler know right we've already done this last line here we have nothing else in our global execution context we're still maybe waiting out here in web browser API land it probably takes a little more than three milliseconds to get something back from Twitter but at some point let's say at some point is around 350 milliseconds we get finally our tweet back from Twitter which is our beautiful high beautiful string high right great so at around 350 milliseconds when we get this string back from Twitter our function is complete now this is a little bit different right did we Joseph did we pass any callback function to the web browser API no no right all we passed it was this URL right the URL that we wanted to send the request to so in this case the web browser API doesn't necessarily know what delayed functionality we want to do but it does know something that fetch sends out to the web api right is that this is a promise off' ID function this is a promise this is a function that has a promise in javascript and so all that the web browser does on complete of this of this particular deferred or this particular long task is it's going to update the status and value on this promise object it's going to take whatever value is passed back from Twitter in this case and it's gonna put that as the value for the promise object and it's going to update the status of that promise object in this case because we successfully got back a value from Twitter right to fulfilled or resolved resolved I think is actually what it goes they successfully resolved right so now over here our status is resolved our value is high and now we're ready to trigger this delayed functionality because in JavaScript we do know what delayed functionality we actually want to run right now where to put this delayed functionality you might be wondering or you might not be wondering you might be assuming that we just put this delayed functionality right here in our callback queue because that's where the lady functionality goes and that's not a that's a pretty fair that's a pretty fair assumption or guess right as to where the stuff goes but there's one other piece of promises that we want to introduce here which is that promises get a higher priority and get some special functionality by using a different cue so not only is there a callback queue here but there is also what's called a micro task queue and the micro task queue works similarly to the callback queue in that nothing that's in the micro tasks you can get pushed onto the call stack until the main synchronous JavaScript thread is clear however the micro task queue gets prioritized above the callback queue so by virtue of our premise if I'd function here this fetch function being a promise our delayed functionality of display instead of getting pushed on to the callback queue is going to get pushed on to this micro task you sweetness so it goes on to this micro task queue and now right this is around let's say 350 milliseconds and since our main JavaScript thread has been clear since 3 milliseconds by the time it hits 350 milliseconds and this display function gets pushed on to the micro task queue we are totally ready for this function to be invoked right so the event loop says okay we're ready to invoke this function so let's get this thing off of the micro tasks you let's push it on to callback queue I'm sorry hum the callback you on to the call stack whew late late well okay so 350 milliseconds well excuse me context clear event loop says all right let's drain the micro task queue takes that display function pushes it on to the call stack Dennis tell me what happens when we invoke a function here in JavaScript we create a execution context that function executes in constant context and great and we actually have a we actually have a function definition here for this one right so let's run this one line by line what's the first thing we do when we start running our JavaScript code no we got so we got console without log data before that so before we before we start running that code line by line right we need to take care of arguments all the data parameters so with that own local memory now absolutely we're gonna put that in the in the local memory of the function level memory what are we actually going to put there that's nobody starts with the you undefined [Laughter] right when we invoke the function we have to pass it something right and in this case when we invoke this function display before we know how it gets this data what do we what do we expect you know just knowing what we've what we've got access to here and and what are what code is set up to do here what were we expect that that value to be whatever it done from fetch yeah so that string high right this is what comes back so we expect that the string high is getting passed to this function got it right so that's totally right I thank you for it for you know playing along with that was a particular yeah I was hoping that you wouldn't know the answer to that one so yeah just before you keep going there I just want to quickly explain how we can assume that that's what we'll get past it it's not really an assumption it is something built into the spec of promises so the way that promises work and the way that promise deferred functionality gets invoked is that promise deferred functionality things that are in this on fulfillment array or for error handling in the non rejection array will automatically be passed when they're invoked it will automatically be passed whatever the current value for that promise is right whatever promise object they were they were attached to that functionality was attached to will automatically be passed the value of that promise object when it's invoked so when the event loop invokes this display function it's automatically going to be passed the value of that promise object at that time which was hot so excellent tennis as we're going through we're setting data now to the string high right so now what are we gonna do what's the what's the next thing we're gonna do when we're running this display function we console dot log and that creates a new execution context and we push that to call stack absolutely we get a new little function execution context here right runs console.log is on our call stack here at around 351 milliseconds we're going to see hi sweet and then right of course these gone sweet and we have nothing left in our main JavaScript thread we've got nothing left in our queues so now we're all done right quick sums on this how do we feel about this promise deferred functionality sweet just as a you know kind of quick recap here right promises are literally just these special objects that are built into JavaScript they're immediately returned to us when we invoke promised permissive ID functions right when we invoke any function that's been built with this promise object inside we immediately get back this promise object that promise object comes with a bunch of built-in features some of those core features that we care about or that we now have in JavaScript a way of tracking the status of that promise knowing that it's pending but it's still out there in Web API land waiting to be resolved we can tell when it's been resolved because that status gets updated the value gets updated with whatever that promise that where that promise resolves to right and then we can attach delayed functionality to that promise object specifically we can attach that in JavaScript so that we can keep track of what delayed functionality is going to be run and we can sort of decouple the asynchronous activity and what we want to do after we've done that asynchronous tasks so we could have potentially permissive ID functions that we reuse in different places the same function that we reuse in different places and we just attach different delayed functionality to it instead of having to rewrite that permissive ID function over and over and over again for different use cases right with callbacks we always have to pass into that callback function what we want to delay so we can't we have a harder time doing things like reusing those functions in other places right also something we didn't look at here specifically in this example but something that comes in handy a lot with promises that not only can we attach using the ven method delayed functionality for when that promise successfully resolves but we can also attach different functionality to go down a different track if that promise rejects or fails to resolve so we had this awesome way of being able to do more specific error handling as well which is great so one last example that I want to walk through which is bringing all of this stuff together because I want to note right that this is not something that is you know it is the kind of the new standard right so new new things that are being written are often using this promise syntax right using these features however set timeout is still a set timeouts the timeouts still under the hood is using or not even on the hood so timeout is still using callbacks you can wrap existing callback functionality in promises you can add a little bit of extra logic to your set timeouts you can wrap those functions in promises that's for a later time a later topic put into the hood right there still using callbacks so let's take a look at sort of priority order and how this stuff kind of all comes together in in you know in a really specific example that brings in all of the things that we've talked about tonight so we're gonna have synchronous code that takes a long time we're gonna have callback functionality that's asynchronous we're gonna have premise off' ID functionality that's asynchronous so let's see in a final example of how this stuff all comes together before we dive into that let's do some some quick questions there's a couple of things in here cool where does the value high get passed into the variable called data um I think that I think that's been answered but if you still have that question let me know Jeremy so the event loop callback queue and micro task queue always exist or do they only start when JavaScript sends something to the browser API ah they always exist right those queues always exist we just don't really ever use them unless or we don't really or see them being used with the exception of these these things they get used potentially for other things under the hood that we never really even talk about in JavaScript or that we never really actively use these are the times that we as JavaScript engineers care about them existing but they do always exist was it the usage of the dot then that passed would got resolved from the xhr high by passing the argument for display yes okay it's been answered sweet yes acts absolutely though Tyler that is that is what happens because we used that Venn method to attach display to that promised object right that special magic that that Zen method works part of that special magic is to make sure that the value that gets passed to the the function we're invoking is the current value of the promised object it's basically wrapping that functionality that we pass into it that display functionality that we pass into it wrapping that with some additional with some additional logic to make sure that it gets the data that it needs when when it's involved okay so do you have to know the type of data that you're gonna be getting back beforehand yeah it's probably good to know what data you're going to get back in the format of that data so that whatever delayed functionality you're using is is using that data in the right way okay this is just a curiosity question but if you if you had a function in the on fulfilment that as part of the on fulfillment property of that promise object that also had a hard-coded argument how would that work so like if you had two arguments one of those being data one of those being a hard-coded argument but is that something you can do or is that something you wouldn't what do you mean by a hard-coded argument like like something you actually passed you pass into the function like like like a number or something like that ah so you'd probably need some sort of like wrapper functionality to be able to do that if your promise object isn't going to provide that it's probably not a delayed function that you want to be using in that particular case right you may need to do something like have an anonymous function that wraps your display function then and passes not only the data that comes in from the promise object but then whatever other data need that function you'd need for that function gotcha I had a question yeah if you invoked you know the fetch call the fetch API call not in global but you called it in some other you know execution context with that promise object be stored in the local memory or with that a promise object be stored in global Oh a great question it does get stored in in that local memory but that's where we get into some some questions that are maybe a little bit outside this the scope of the of the talk where we're still able to run that delayed functionality we still have reference to that object in memory outside of the context that it's scoped to in JavaScript so we only have access in JavaScript to it in that function level memory but remember that that function level memory being scoped is scoped in JavaScript but it's still just living in a memory space allocated somewhere on a machine so it still exists outside of just that context little outside the scope of what we're talking about but is a good question yes it's still scoped in JavaScript to the context in which we define it but is technically still available outside of that scope outside of JavaScript syncing weight stuff is that like oh like synthetic synthetic sugar for promise it's kind of like its own thing going on yep absolutely I'm gonna touch a little bit on async await at the very end and tell you why we don't talk about it a little bit more in this particular in this particular lecture but great question I'm gonna get there sweet all right let's do this final example and then we'll round out with some final questions at the end already so this is what we're gonna go through if you thought the last one was hard to read let's take a look at this one so let's take a look at this one beforehand first things first we are just going to be right we're just going to be looking at defining some functions in the beginning right we're still gonna have our display we're still gonna have our print hello now we're bringing back that block for 300 milliseconds this time instead of one second because whoo we want to be a little different we're still getting a set timeout this time we're combining that with a permissive ID function that fetch we're doing that synchronous blocking of blocking for 300 milliseconds and we're console logging me first which will run first we can only hope that it's still be first all right here's all the things everything is set up I promise we're not introducing anything new any new pieces of the diagramming we're just gonna make sure that we're all on the same page about how this is working so kick us off brenn what's happening first line here uh it's really hard to see thanks yeah so we're declaring a function called display and global memory with a function definition next line and we are declaring a function definition labeled print hello next one another function definition labeled block for 300 MS sweets next one we are calling set timeout or invoking sceptile and that's an API call we will not be calling that with synchronous JavaScript so amazing yes we hit this we hit this set timeout what arguments are we gonna pass to this set timeout we are passing at the function definition labeled print hello in our global memory and then the number 0 and number 0 and you are exactly correct we are not going to run this like synchronous JavaScript but instead we are going to do what we will be calling the web api and do you remember what specific feature of the web api we're gonna call timer yeah timer right so we're gonna use the timer feature out here in the web api to handle doing this long task of setting a timeout but that's all we're gonna do in JavaScript right we're gonna pass it out there once it's done once we're done passing it out there we're gonna move on right along in JavaScript and what's the next line that we're going to hit in JavaScript Joseph sorry I can't really see oh no sorry here we go we just ran set timeout we've passed that off to the Web API whoa pass that off to the Web API what are we gonna do next okay so we're declaring a constant future data and we say fetch with the the link to the Twitter yes so just to be clear right we're not setting it to the fetch right we're gonna we're gonna in global memory right we're going to define this this constant with the label future data its value is eventually going to be something but for now right we need to invoke whatever fetch is so for now it's gonna be undefined right before I have you move on though Joseph right we're going to pause here this is the line that JavaScript moves to but let's quickly round out the Web API here we we had passed something out to the Web API and I want to make sure that we that we document that so the web browser API right is going to check if something is complete and then once it's complete it's going to do something right on completion we're going to do something first thing that we have out here right is our timer and that's going to be taking in a function definition in this case print hello and a weight of zero milliseconds so out here at one millisecond when this when this timer starts Bren you were running me through this when we're out here on the web api at one millisecond this this function comes out here are we done running the timer yes we are yep so what do we do on completion of this set timeout we push the function definition print hello to the callback you yeah absolutely right what we want to do on complete is say that this print hello function is ready to be invoked so we take that and we push it on to the callback queue here write this function print hello comes on here at roughly 1 millisecond sitting out here hanging out in the callback queue amazing now back to JavaScript land and Joseph you were running me through the future data constant here so tell me what are the two things that happen when I invoke this fetch it creates a promise object absolutely we immediately get returned to us and Crom this object we'll talk a little bit more about that in a second what's the second thing that it does and it pushes on to the Web API yeah it sends this task out to the Web API do you remember what feature of the Web API we use for this one HS sorry x HR yep xhr do you remember what it stands for HHH it's called HTTP request yep XML HTTP request we're going to specifically in this case use the xhr feature uh do you remember Joseph what the xhr feature what that does since a request to Twitter to Twitter and so at roughly let's say we get out here at 2 milliseconds at 2 milliseconds is this function complete mm-hmm have we gotten our tweets back from Twitter yet I don't think you know yet is that correct no right yep so it's not complete yet at 2 milliseconds we're still waiting right this this request has just been sent off to Twitter we haven't gotten anything back yet so at 2 milliseconds we're still kind of hanging out here in web browser API land just waiting for that that tweet those tweets to come back meanwhile back here in JavaScript land let's dig in a little bit more into this promise object so you're totally right we get immediately returned to us in JavaScript this delightful promise object I'm going to reallocate my board space here a little bit more let's move this down and let's say that we want to have future data be this whole big promise object here and then let's put console back down here good okay so future data is very briefly before we actually fully invoke this fetch function very briefly undefined soon as we invoke this fetch function we get immediately returned to us in JavaScript land this promise object right tell me whoops tell me Joseph two of the things that we care about on this promise object the status and value yeah and what does the status default to pending pending absolutely what does the value default to undefined absolutely undefined amazing thank you so much Joseph all right now still in JavaScript land we move on so whatever the next thing is at around two milliseconds tell me Kate what's the next thing we move on to you must lay down a little bit please can't see oh yes here we the next slide oh sorry so to be clear we just finished this line but we're now up here on this line and then we we involved the method display so very close we invoke the then method and we pass it the function definition for display right so we're invoking this then method and we're passing it the whole function definition for display great and so tell me Kate what do we actually do with this function definition here that we pass into the bed method where does that go absolutely it gets pushed into this array on the on fullfillment property on that promise object and we just push in that display function definition right it's now been wrapped with some other functionality by that then method right but essentially what we're doing is we're taking that display function definition that's specially wrapped display function definition and pushing it into that on fulfillment array awesome thank you so much Kate next what are we gonna do Tyler you still there yeah I'm here but my mic didn't work the last time Tyler tell me what are we gonna do on our next line then around three milliseconds we're looking at a function that's called block for 300 milliseconds no art yet and what happens when we get to this line what are all the steps that we're gonna they were gonna do here at this line a new execution context it's created absolutely it does what happens to our call stock and we've added we get block for three hundred milliseconds just above global on our call stack yeah get the push block for three hundred milliseconds on to our call stack there and then what happens in block for three hundred milliseconds do we know we block for 300 milliseconds yeah exactly right we block for 300 milliseconds somehow right Yeah right Tyler do you remember what what one way we could block for 300 milliseconds what's what's something we could do we could run a loop for a little while long loop yeah yeah exactly right block for 300 milliseconds so we're gonna add 300 milliseconds in here somehow probably with some sort of some sort of loop awesome Thank You Tyler we're gonna pause in there for a minute while that block for 300 milliseconds is running and we're gonna revisit our Web API out here so let's say while that block for 300 milliseconds is running twitter comes back out roughly let's move this around a little bit so we have a port space right at two milliseconds this xhr was not complete but let's say around 250 milliseconds now we've gotten our tweets back from Twitter in this case our singular tweets back from Twitter and so Joseph right you were running me through the xhr part of this what do we want to do when this xhr is complete it updates the status and value for the promised object yeah goes into memory updates that status to resolved right and that value what are we gonna update that value with with high with high right string high so sweet up here status becomes resolved value becomes high great now because that status has updated to resolved and the Val we have a value now and because it was resolved and not rejected right it didn't fail we're ready to uh you know invoke the functions in this on fulfillment array but we can't quite do that yet right Joseph so what do we do with the functions in this on fulfillment array you push into micros ask you absolutely we do right so we take this function definition here and we put it on to the micro task queue over here it's gonna be that display that display function definition and that comes in here around let's say 250 milliseconds right awesome Thank You Joseph so let's run back here into JavaScript land let's say that now block for 300 milliseconds is finally done so out here we come around 303 milliseconds tell me Tyler what happens when we're done running this block for 300 milliseconds function and we're looking at our next line in JavaScript before we're looking at the next line what happens when we get done running a function what happens to our call stack to our local execution context the local execution context goes bye-bye and also the block for 300 milliseconds gets popped off the call stack absolutely thank you so much sweet so now 303 milliseconds back out here in our global execution context tell me then give Kenny what happens in our global execution context what else do we have to run out here oh oh so we pop we called blog for 300 milliseconds of that's finished we popped it off the call stack oh and then we Delocated it right well optically located and then so I think we just go to the next line right yep so what line are we at now consoled Ella sweet run me through that console.log so we are creating another execution context yep and what else happens to a call stack we're gonna push that in across that I'm just gonna make a really tiny execution context here because I'm running out of space just so fast console.log pushed onto the call stack here right in our console then first thing that we're gonna see luckily right first thing we expect around three hundred and three milliseconds we're gonna see that me first awesome now that that's done running give Jenny what happens to this local execution context so once once we the the method is done it's got a deal okay and it's gonna get popped off the coast at absolutely awesome thanks Annie sweet so now around three hundred and four milliseconds our global thread our global execution x-ray is done running well we have no more synchronous code to run right all done with that console.log was the last line here now the event loop I see is that that JavaScript thread is clear and says all right let's check those cues right got some stuff in the queues so tell me then Dennis what is the first cue functionality that's going to get that's gonna get put onto the call set push on to the call stack no this play is gonna go up to the call stack yeah how come display is gonna go on to the call stack it's only been here since the 250 milliseconds are come it's not gonna be this callback queue one priority it's got priority yeah it just is right oh sweet so absolutely display is going to be removed from the micro task you it's going to be pushed on to the call stack right so tell me that Dennis right display gets pushed onto the call stack around three hundred and four milliseconds uh and display takes in an argument right what are we gonna pass to display the value of the promise just nobody huh which is currently high right awesome sweet not his high awesome we get a new function level execution context right what are we doing in our display of high in this function level execution context nope sorry there you go work on console logging high so we're gonna create a lot of execution context within that I'm gonna push that to the call stack and then console.log high put it in the console and there we go everything awesome yeah absolutely right around three hundred and four milliseconds we're gonna see in the console and then of course back here we're going to be done running console log we're going to pop that console log off the call sack then we're gonna be done running display so we're gonna move we're gonna pop display off the call stack and then we're gonna be back out here around three hundred and five milliseconds and now what are we gonna do Peter what's gonna happen now here at three hundred and five milliseconds we are going to push that function from the call back you under the under the call stack absolutely so off the callback queue and on to call stack print hello what happens here when we invoke print hello we're going to create a new function level execution context definitely we are great what happens inside print hello we're gonna log the string hello to the console which requires you to push the console dot log or the dot log method on the console to the call stack and then open up another function level execution context within print hello absolutely it does thank you so much right so great we're running console log then over here around three hundred and five milliseconds we are going to see hello and then of course when we're done running all these functions what happens Peter we're going to deallocate all that memory that we allocated initially for the local execution context of console dot log log and do the same thing for print hello absolutely that's what we're gonna do whoa thank you so much Peter and then back out here in our global execution context around three hundred and six milliseconds now what are we going to do you get any what are we gonna do next ah I was still trying to fall all oh well I was we have you don't have anything on the the queue when the call back you and the market to micro test queue arm so there's nothing there that's a bird on me and we don't that was a trick yeah but it's but it's a good one too it's you know a good step to do at the end of everything right is you know we may think that we're done but you know always good to make sure right all of our synchronous code is doing our micro task queue is done our callback queue is done so yeah so we are good to go we have done all the things that we needed to do right we've diagrammed through not only running synchronous JavaScript code not only running asynchronous JavaScript code with callbacks but also running asynchronous code with promises and doing it all together and we see kind of the order in which these things happen and so kind of in summary right when we talk about promises this is super super helpful right it takes on a whole new level of being able to track through our JavaScript code and our asynchronous JavaScript code inside JavaScript right we don't have to just rely on passing in a callback to some you know random function right or not even random but passing off this this delayed functionality just passing it in as a callback function and hoping that at some point it gets looked right now we have a little bit more control a little more explicit control in JavaScript about what delayed functionality is going to run and if it's going to be run on a successful condition or if it's going to be wrong on our failure condition right we have a little bit of a way to track through inside JavaScript the status of that of that asynchronous activity the current value of that asynchronous activity some things we didn't get a chance to talk about tonight or that kind of are just next steps of things to look into our promise chaining right so what if we want to grab a tweet from Twitter like we're doing here with future data and then instead of just displaying it maybe we want to display it but then maybe we also want to get some more details about the author of the tweet right we want to get the followers of that particular author or the comments that were replies that were were sent for that tweet right so we might want to have a bunch of chains of promises so we first want to get one tweet we want to display that tweet then maybe we want to go and fetch all of the replies for that tweet then maybe we want to display those those replies for that tweet all of that if this were non-permissive ID if this was just using callbacks would have to be in one giant kind of messy code block right but now with promises we can actually do promise chaining so we can have future data then display dot then fetch replies dot then display replies right and we can see all of that in you know kind of right in line in JavaScript it's very clear the order in which things are going to happen and we can still have error handling that is either specific to each of those individual chains or we can attach an overall error handler if at any point in this chain something fails just catch that an error has happened and do something else right break out of this chain and instead go to this error and run this error function so we have a lot cleaner error handling with promises but again we still have that little bit of a problem that a lot of people don't know how this works and you're getting you asked earlier about async await which right if you kind of look up anything about asynchronous activity in JavaScript anything new an asynchronous JavaScript right you're gonna see a ton of example the ton of articles and a ton of things about async await the reason that we don't talk about it in this in this workshop is that it's more syntactic sugar on top of promises you should still know if you really want to understand async await you need to understand how these raw promises work under the hood right because it's all using this this promise functionality under the hood there are some additional benefits definitely a lot of syntactic benefits to using async/await but to really understand how your asynchronous code works promises are the first first stock right async/await is another layer on top of it that's more of a deep dive and requires you to also just know some other features of es6 so it doesn't really work for this particular workshop but would kind of be the next step to go once you're feeling pretty confident in in promises awesome let me just make sure that I'm not missing any particular things in the slides here and then I will move to two questions in one second I did it again where I let my screen die well there we go okay yep this is more just a recap slide again you'll have access to these slides oops again you'll have access to these slides afterwards so so you'll be able to see all this but this is basically just a recap slide of being able to see that we have the micro task queue we have the callback queue kind of they have a priority order right and so just to recap on that and now we can delay functions running until the work is done and the data is available right this is a huge driver for modern web applications any web application that you that you're using particularly anything that's run with some sort of front-end framework like react or angular or view right all handily reliant on this ability to do asynchronous activity awesome we don't have any pair programming tonight but I would love to take any final questions and then we'll go to the slack out the fast-track application code which is something that you're probably waiting on so let's see I'm gonna go look back at the comments feel free to shout out questions if you have a question regarding the micro test - is that does the hierarchy or the president's then it gets to run depend on the particular Web API that's involved residence yeah the order the priority I guess I'm mentioning does that depend on which of the web api is get invoked I think I missed that ah so the priority for this asynchronous functionality depends on whether or not you're the function that you're using the facade function that you're using right my confusion is how does it know to go back to go to the callback queue versus the Marco task queue yep so callbacks callback queue promises micro tasks you anything that's deferred and delayed using promises micro test queue anything that's not using promises but instead is just using this kind of callback pattern callback you easy enough thank him yep totally you all right Robin said so assuming there are a number of functions running after display display takes 500 milliseconds to fetch data from Twitter while the other functions are running asynchronously so will it slot right back after it is done ah I see so I think I understand this question but I just want to I just have some clarifications here so when you say there are a number of functions running after display are you talking about synchronous functions or asynchronous functions it looks like you mean asynchronous functions about a hundred percent sure I might want to just chat with you afterwards about that particular use case because it depends it's honestly going to depend on the order in which this asynchronous functionality is invoked as well as the order in which it is resolved and how how quickly other things are being pushed on to the micro tasks you so for now the answer is it depends and then in general how do we find out what the data type of the value xhr will return when we call fetch with a link great question documentation right so in this case we were we were sending a fetch out to Twitter or the Twitter API so the Twitter API is going to have a whole set of documentation around how it returns data and what type of data it returns it will probably never actually be a string most likely it would be some sort of JSON data that you'll have to parse through but not always but more likely than not that's that's how Twitter's gonna return your data but a great way to know how the data is going to be returned API documentation right documentation for wherever you're fetching the data from well Jenny says I'm curious about the mechanism by which the callback in then callback is triggered is it sort of like upon studying the promised objects value property the browser API checks to see if there is a non filmer property and as it's the micro task queue if so great question that is a great place to start looking at the promised documentation mdn has awesome resources on how this promised object work the different methods that are applied to it there's also just kind of looking at the spec for like the es6 spec will give you a lot of those kinds of answers it has very detailed information about kind of the order in which things happen the way that this functionality gets pushed on to the micro task queue for now it's a little - it's a little too heady to get into tonight but the great place a great place to look for that is the actual spec for for promises or something like mdn it'll give you exactly kind of line by line how it gets from from the web api back into kind of JavaScript lands the micro tasks you when you call then it pushes the function on on to the on fulfilment absolutely that is one of the things that the then method does is it pushes it into this somewhat array it does so kind of after wrapping whatever function definition you pass into it with some more with some more logic so it basically takes our display function and wraps that display function definition that we pass it with some more logic to make sure that when this promise gets resolved that that display function is actually getting invoked with the proper data right that it's actually getting invoked with the value of the promise object a great thing and another great way to get more of a sense of how that mechanism works is to look into writing your own promises because you get a sense of what's actually happening in a fetch right specifically that fetch inside of it has baked into it creating this new promise object invoking that fetch and then making sure that whatever that additional functionality is gets passed the value that that comes back from that fetch request right so taking a look at creating your own promises from scratch when it's done the value we set when it's done the value we set and then whatever functions are in the on fulfillment it will be call will all be called with the value correct yes and just clarify in my mind the micro tasks and callback you both wait until all the synchronous JavaScript executes and then is a thing of priority on both right yes so exactly so any functionality in the micro tasks or callback you is going to wait until synchronous JavaScript code runs and finishes and then the priority is always going to be micro task queue prioritized over callback you cool NBN is the best they're all correct is there a way to synchronously check if there is any asynchronous functions in the micro callback you and then forcefully invoke them assuming that it would be bad software development so I don't I'm not gonna necessarily comment on bad software development but the answer is that you can't do that so you can't like forcefully invoke at least not in JavaScript you can't forcefully invoke any of this asynchronous functional you can't change the priority order the spec is the spec and as long as the browser's have implemented the spec accordingly this will run in this order every time there's no way in this particular case to hijack those queues and and forcibly invoke them which is a good thing great it's been so lovely meeting all of you have a great rest of your night morning whatever time it is for you
Info
Channel: Codesmith
Views: 2,187
Rating: 5 out of 5
Keywords: javascript, coding, computer science, asynchronicity, codesmith, fullstack javascript, software engineer, learn code, learn to code, web developer, web development, react, redux, node, coding bootcamp, coding bootcamp la, coding bootcamp ny, coding bootcamp nyc, software engineering, software engineering immersive, javascript functions, javascript objects, basic javascript, intro to coding, intro to javascript, javascript looping
Id: O_BYLu0POO0
Channel Id: undefined
Length: 70min 47sec (4247 seconds)
Published: Tue Apr 07 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.